C++ Notes: Reading Lines

These notes are written using cin as an example, but they apply to all input streams.

What kind of strings?

Strings (sequences of characters) are stored two different ways in C++. C-strings are arrays of characters with a terminating zero value at the end. There is also a string class in the C++ standared library. In general, it's better to use the string class, but many times that C-strings must be used because the string class was not available when many other classes were developed.

Reading a line into a string

   string s;
   . . .
   while (getline(cin, s)) {
      // s contains the input line, without final newline char.
      . . .
   }

Reading a line into a C-string

   char ca[100];
   . . .
   while (cin.get(ca, 99)) {
      // ca has one input line without crlf and with terminating 0
      . . .
   }