2010-03-03 58 views
1

只是一个简单的问题。没有等待在C键盘输入(重载输入流运算符)++

我已经开发了下面的代码:

#pragma once 

#include <iostream> 
using namespace std; 

class Percent 
{ 
public: 
    friend bool operator ==(const Percent& first, 
           const Percent& second); 
    friend bool operator <(const Percent& first, 
           const Percent& second); 
    friend Percent operator +(const Percent& first, const Percent& second); 
    friend Percent operator -(const Percent& first, const Percent& second); 
    friend Percent operator *(const Percent& first, const int int_value); 
    Percent(); 
    Percent(int percent_value); 
    friend istream& operator >>(istream& ins, 
           Percent& the_object); 
    //Overloads the >> operator to the input values of type 
    //Percent. 
    //Precondition: If ins is a file stream, then ins 
    //has already been connected to a file. 

    friend ostream& operator <<(ostream& outs, 
            const Percent& a_percent); 
    //Overloads the << operator for output values of type 
    //Percent. 
    //Precondition: If outs if a file stream, then 
    //outs has already been connected to a file. 
private: 
    int value; 
}; 

而这正是实现:

// [Ed.: irrelevant code omitted] 

istream& operator >>(istream& ins, Percent& the_object) 
{ 
    ins >> the_object.value; 
    return ins; 
} 

ostream& operator <<(ostream& outs, const Percent& a_percent) 
{ 
    outs << a_percent.value << '%'; 
    return outs; 
} 

问题是,当我尝试使用重载的输入流运营商的程序没有做任何输入输入一个值后不等待输入 - 在一系列输入中。换句话说,这是我的主要功能:

#include "stdafx.h" 
#include "Percent.h" 
#include <iostream> 

using namespace std; 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
    cout << "Please input two percent values and an integer value: "; 
    Percent first, second; 
    int int_value; 
    cin >> first; 
    cin >> second; 
    cout << "The first percent added to the second percent is: " 
     << first + second << endl; 
    cout << "The first percent subtracted from the second is: " 
     << second - first << endl; 
    cout << "The first multiplied by the integer value is: " 
     << first * int_value << endl; 
    return 0; 
} 

它只是跳过他们,像他们未初始化变量会被分配值 - 除了第一个变量,它确实得到一个值。

我的问题是我要如何防止这种行为?

+0

请使用“代码saple”格式来编辑您的文章 – Ando 2010-03-03 16:14:44

+0

请格式正确 – Andrey 2010-03-03 16:14:53

+0

这次您格式化得太多:) – Ando 2010-03-03 16:18:29

回答

0

一切工作正常,我(只是复制粘贴您的代码),除了最后COUT < <抛出错误,因为int_value未初始化

+0

啊奇怪 - 可能是编译器的事情。 – hairyyak 2010-03-03 16:22:45

+0

除非你使用相同的编译器 – hairyyak 2010-03-03 16:23:46

+0

我是使用Visual Studio 2008 – Andrey 2010-03-03 16:26:57

2

与输入流,特别是在Visual C++的一个共同问题,就是你需要。忽视()。这将防止输入被忽略。如果我没有记错,只需在第一个cin之前(或之后)执行cin.ignore()。我认为应该这样做。

0

我想那是我,因为我输入一个百分比,当我应该已经输入一个整数,约占为什么它工作正常在安德烈的编译器 - 还有,我也没有读百分号,我认为这是没有帮助。

输入和输出都应该以百分号被succeded。