2.4.5 Creating an Input Stream from a String
String Input Stream
First, starting at the top of your program, you need to include sstream
, the string stream library.
#include <sstream>
Next, create a string an input string stream object.
string line;
istringstream iss(line);
Now, iss
can be used just like cin
or a file input stream.
Three-Argument `getline` Call
We've seen the standard two-argument call to getline
:
string line;
getline(cin, line); //(input stream, destination)
getline
can also be called with three arguments
string token;
char delimiter = ' '; // if you want to use a space character as a delimiiter
getline(cin, token, delimiter);
getline
returns the number of characters read in from the input stream, including the new line character (\n
), but not including the terminating null byte (\0
).
string line;
istringstream iss(line);
string token;
while (getline(iss, token, ';')) // assuming you want to use ; as a delimiter
{
// read from the string
}
This works because, in C++, any non-0 number is the equivalent of true
, while 0 is the equivalent of false
.
Remember, true is stored as 1 and false is stored as 0 in C++!
Try This Example
Last updated