Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make it read cin twice?

Tags:

c++

cin

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?

like image 701
Liz Z Avatar asked Feb 01 '26 02:02

Liz Z


2 Answers

You need to clear cin. It's reading in the 'enter' from the previous cin.

cin.clear();

And I also remember doing something along the lines of:

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

More information in this post:

How do I flush the cin buffer?

like image 170
Tyler Ferraro Avatar answered Feb 02 '26 14:02

Tyler Ferraro


I bet you did not read the i character from the input stream

like image 44
Martin York Avatar answered Feb 02 '26 16:02

Martin York