Mfroa
Mfroa

Reputation: 3

last input not working after exiting the while loop

just curious on how to fix this minor issue for cin.

int main(){

    int x,w;
    while(cin>>x){
         cout<<"This is x -> " << x << endl;
    }

    //now this cin will not be executed

    cin>> w;

    cout<< "This is w -> "<< w << endl;

    //prints some garbage value for w

}

the last cin is being skipped, and prints some garbage value for w, im certain its the way the cin function works, but im not entirely too sure on how to fix the error. I tried cin.clear(), and cin.ignore(), but im unsure of what parameters to put in.

Upvotes: 0

Views: 255

Answers (2)

Linear Data Structure
Linear Data Structure

Reputation: 342

You get garbage value when the While loop terminates because you have to clear the invalid input stream and then read the standard input before taking another value from the user. I have done something for you. I think it might help you

int main() 
   {
    int x, w;
    while (cin >> x)
    {
        cout << "This is x -> " << x << endl;
    }

    cin.clear();  //removing the invalid input from the stream
    getchar();    //reads from standard input
    cout << "Enter w : " << ' ';
    cin >> w;
    cout << "This is w -> " << w << endl;
    return 0;
}

Output

5
This is x -> 5
4
This is x -> 4
3
This is x -> 3
t

Enter w :  10
This is w -> 10

Upvotes: 0

Jarvis
Jarvis

Reputation: 8564

When you exit from the while by entering an incorrect data type (non-numeric input), you need to remove the invalid input from the stream. You can do it like this:

while(cin >> x){
    cout << "This is x -> " << x << endl;
}

std::cin.clear();
std::string str;
// read the invalid input from stream in some string 'str'
std::getline(std::cin, a);

// now you can take input normally
std::cin >> w;

You need to #include <string> for above as well.

Upvotes: 1

Related Questions