只是一个简单的问题。
我开发了以下代码:
#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 :(得分:2)
输入流的一个常见问题,特别是在visual c ++中,是你需要.ignore()。这将防止输入被忽略。如果我没记错的话,就在第一个cin之前(或之后)做cin.ignore()。我认为应该这样做。
答案 1 :(得分:0)
除了最后一个cout&lt;&lt;之外,一切都适合我(只是复制粘贴你的代码)抛出错误,因为int_value未初始化
答案 2 :(得分:0)
我认为是我,因为我输入一个百分比,当我应该输入一个整数,这说明为什么它在Andrey的编译器上正常工作 - 我也不读百分号,我认为不是帮助
输入和输出都应以百分号结束。