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

問題は、オーバーロードされた入力ストリーム演算子を使用して入力を行おうとすると、一連の入力で1つの値を入力した後、プログラムが入力を待機しないことです。つまり、これが私の主な機能です。

#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

特にビジュアル C++ での入力ストリームに関する一般的な問題は、.ignore() が必要なことです。これにより、入力が無視されるのを防ぐことができます。私の記憶が正しければ、最初の cin の直前 (または直後) に cin.ignore() を実行してください。そうすべきだと思います。

于 2010-03-03T16:30:15.457 に答える
0

整数を入力するべきだったのに、パーセントを入力していたのは私だったと思います。これが、Andrey のコンパイラで正しく機能した理由の 1 つです。

入力と出力の後にはすべてパーセント記号を付ける必要があります。

于 2010-03-03T16:41:17.003 に答える
0

int_value が初期化されていないため、最後の cout << がエラーをスローしたことを除いて、すべてが適切に機能しました (コードをコピーして貼り付けただけです)。

于 2010-03-03T16:21:24.517 に答える