How do we read all characters from the input stream; including blanks, tabs, and new-lines?
This could be a input file stream or something else, like standard in.
The extraction operator doesn’t read white space or characters.
You can use get functions to read a character:
ifstream inFile;
char nextChar;
nextChar = inFile.get();
You can use getline to read a line of characters from a text file.
char lineBuffer[bufSize];
infile.getline( lineBuffer, bufSize );
float price;
char productName[20];
char fileName[] = "test.txt";
ifstream inData;
inData.open( fileName );
inData >> price;
inData.getline(productName, 20);
cout << price << endl;
cout << productName << endl;
The newline character is still in the stream buffer, and that is interpreted as an empty string.
So, we need to clear the buffer ...
inData >> price;
inData.ignore( 20, ‘\n’ );
inData.getline(productName, 20);
34.99
Motor Oi
It’s often unreasonable to forecast the input length.
So we can use this form ...
getline(cin,input);
This has a default delimiter or endpoint of \n, that’s a new line.
But you can change this ...
getline(cin,input,’t’);
Be careful with this, you can capture a lot more than you expect.
Use put() in a similar way to get().
You can use output manipulators if you want to format your output:
cout << setiosflags(ios::fixed);
cout << setiosflags(ios::showpoint);
cout << setprecision(2);