3

I have this bit of code:

... 
ComplexNumber C1;
ComplexNumber C2;

cout << "Enter a complex number C1:" << endl;
cin >> C1;
cout << C1 << endl;
cout << "Enter a complex number C2:" << endl;
cin >> C2;
cout << C2 << endl;
...

but as I've discovered it won't wait for user input the second time and will simply leave C2 with the default value I've defined for the zero-arg constructor in the ComplexNumber class and move on.

All the solutions I've found to this issue use getline() instead of cin >> , but this assignment is to test how well we've overloaded the opperator >> for our ComplexNumber class, so I think using getline would defeat that purpose. Is there another way to make this work?

EDIT: @Martin you were correct! It works after I changed my operator>> to:

istream & operator>>(istream & in, ComplexNumber & n) 
{
    int inreal=0;
    int inimag=0;
    in >> inreal;
    char plus;
    in.get(plus); // read the plus sign since it's a char
    in >> inimag;
    char i;  // DID NOT HAVE THIS LINE AT FIRST
    in.get(i); // DID NOT HAVE THIS LINE AT FIRST
    n = ComplexNumber(inreal,inimag);
    return in;
}

Thank you so much!

Since I'm new to the forum I don't know how to give credit to a sub-comment; is it okay if I just give the green check to the one official reply on this post?

4

2 に答える 2

2

cinをクリアする必要があります。前の cin から 'enter' を読み込んでいます。

cin.clear();

また、次のようなことをしたことも覚えています。

cin.ignore(cin.rdbuf()->in_avail());

この投稿の詳細:

cin バッファーをフラッシュするにはどうすればよいですか?

于 2011-04-20T23:33:53.903 に答える
1

入力ストリームから i 文字を読み取っていないに違いない

于 2011-04-21T00:38:40.113 に答える