1

只是一个快速的问题。

我开发了以下代码:

#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;
}

它只是跳过它们,变量得到赋值,就像它们没有被初始化一样——除了第一个变量,它确实得到了一个值。

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

4

3 回答 3

2

输入流的一个常见问题,尤其是在 Visual c++ 中,是您需要 .ignore()。这将防止输入被忽略。如果我没记错的话,只需在第一个 cin 之前(或之后)执行 cin.ignore() 。我认为应该这样做。

于 2010-03-03T16:30:15.457 回答
0

一切对我来说都正常(只是复制粘贴了你的代码),除了最后一个 cout << 抛出错误,因为 int_value 没有初始化

于 2010-03-03T16:21:24.517 回答
0

我认为是我,因为我输入了一个百分比,而我应该输入一个整数,这解释了它在 Andrey 的编译器上正常工作的原因——我也没有阅读百分号,我认为这没有帮助。

输入和输出都应以百分号结尾。

于 2010-03-03T16:41:17.003 回答