Hi there,

Say I have the following while loop, that loops on the condition that a lne (a string) is received from a file:

while ( getline( inData2, line ) )                  // Increment rows till none left
    {
            if ( !line )
            {
                cout << "No data entered. Please enter data. Program terminated." << endl;
                exit(0);
            }
      ....
    }

1) How do I check whether there is no line (string) received? Writing !line doesn't seem to work.
2) Is using exit(0) the best way to termine the program of no lne is entered?

int linecnt;

for (linecnt=0; getline(inData2,line); linecnt++) {

}
if (linecnt == 0) {
   // no lines report...
   return; // return value - return false, for example
}

Now if (!line) is a wrong and senseless construct. No operator!() for std::string. You have a line (may be empty) in the loop body (see your own loop condition ;))...

It's not the best method to exit() from C++ functions: local variables destructors are not called in that case. Better avoid C++ program termination with exit().

Thanks for your help, ArkM!

Just a question though... I don't want to terminate only the function (so I don't want to use return), but rather the whole program from within the function. How could I do that without exit()?

>Just a question though... I don't want to terminate only the function (so I don't want to use return),
>but rather the whole program from within the function. How could I do that without exit()?
Check for errors in the main function, and if one has occurred, close it from there.

bool my_function() {
  /* Code Here */
  
  if ( /* Some Error */ ) {
    return 1;
  }

  return 0;
}

int main() {
  if ( my_function() == 1 ) {
    return 0;
  }

  /* Other Code Here Never Executed */

  return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.