Search code examples
c++for-loop

C++ homework (while loop termination)


  1. Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating '|' is entered.

How do you write this?

When I check to see if either int is equal to | they never do because their value is zero if | is entered. My program currently repeats forever if | is entered. I don't know how to access the correct value of the non int | by using ints nor how to stop it from repeating forever.

1 - #include <iostream>
2 - 
3 - using namespace std;
4 - 
5 - int main()
6 - {
7 -     int val1=0, val2=0;
8 -     while(val1 != '|' && val2 != '|')
9 -     {
10-        cout << "Enter 2 integers, terminate with \"|\"" << endl;
11-        cin >> val1;
12-        if (val1 == '|')
13-        {
14-            return 0;
15-        }
16-        cin >> val2;
17-        if (val2 == '|')
18-        {
19-            return 0;
20-        }
21-        cout << val1 << " " << val2 << "\n\n";
22-    }
23-
24-    return 0;
25- }

Solution

  • Instead of reading val1 and val2 directly from stdin, read a line of text. If the line does not start with |, extract the numbers from the line using sscanf or istringstream. If the line starts with |, break out of the while loop.

    #include <stdio.h>
    #include <iostream>
    
    using namespace std;
    
    const int LINE_SIZE = 200; // Make it large enough.
    
    int main()
    {
       char line[LINE_SIZE] = {0};
       int val1=0, val2=0;
    
       // Break out of the loop after reading a line and the first character
       // of the line is '|'.
       while( true )
       {
          cout << "Enter 2 integers, teminate with \"|\"" << endl;
    
          // Read the entered data as a line of text.
          cin.getline(line, LINE_SIZE);
          if ( !cin )
          {
             // Deal with error condition.
             break;
          }
    
          // If the first character of the line is '|', break out of the loop.
          if ( line[0] == '|' )
          {
             break;
          }
    
          // Read the numbers from the line of text.
          int n = sscanf(line, "%d %d", &val1, &val2);
          if ( n != 2 )
          {
             // Deal with error condition.
             continue;
          }
    
          cout << val1 << " " << val2 << "\n\n";
       }
    
       return 0;
    }