[Solved] C++ homework (while loop termination)


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;
}

1

solved C++ homework (while loop termination)