Search code examples
c++if-statementwhile-loopbreakpeek

closing while(cin.good()) loop properly


I'm trying to make the program exit properly without it. I have '|' as my exit, if its the first thing I do when first running, it closes fine. But after entering values and printing them, afterwards entering '|' to exit. It prints out: "The smaller value is 0 The larger is previous second value" // want to remove this from showing

int main()
{    
double first = 0, second = 0;
while(cin.good()){
    char exit;
    cout << "Enter '|' to exit.\n";
    cout << "Enter two numbers:";
    cin >> first >> second;
    exit = cin.peek();

    if(exit=='|'){
        break;}
    else{
        if(first<second){
            cout << "\nThe smaller value is " << first << "\nThe larger value is " << second << endl;
        }
        else if(first>second){
            cout << "\nThe smaller value is " << second << "\nThe larger value is " << first << endl;
        }
    }
  }
}

Solution

  • In your code, you've assumed that the input from your users will be limited to something usable as a double. This isn't necessarily the case. The issue that you're running into isn't related to the statement exit = cin.peak(); but to cin >> first >> second; You can test this by entering any non-numerical input into your program and watching it fail by assigning a 0 to the first and leaving second as is.

    In short, because the conversion of the input into a double fails, you get an indeterminate value for first and then your program moves on.

    You can use the following code as an example. In this, I first populate my variables as strings, then attempt a conversion after the fact.

    #include <iostream>
    #include <string>
    #include <stdlib.h>
    using namespace std;
    
    int main()
    {    
    string str_first, str_second;
    double first = 0, second = 0;
    while(cin.good()){
        cout << "Enter '|' to exit.\n";
        cout << "Enter two numbers:";
        cin >> str_first >> str_second;
    
        if( (str_first.compare("|") == 0) || (str_second.compare("|") == 0) ){
            cout << "\nThanks for playing\n" << endl;
        break;}
        else{
            first = strtod (str_first.c_str(), NULL);
            second = strtod (str_second.c_str(), NULL);
            if(first<second){
               cout << "\nFirst is small: The smaller value is " << first << "\nThe larger value is " << second << endl;
            }
            else if(first>second){
                cout << "\nSecond is small: The smaller value is " << second << "\nThe larger value is " << first << endl;
            }
        }
      }
    }