"cin → x" does not consume a newline character from the input stream, so the next line you extract with getline will contain an empty line. One way to solve this problem is to use getline to extract input line by line and use stringstream to tokenize each line. After you have extracted all the data from the string stream, the key is calling stringstream :: clear () to clear the EOF flag set in the string stream so that you can reuse it later in the code.
Here is an example:
#include <iostream> #include <sstream> #include <string> using namespace std; int main() { string line; stringstream ss; getline(cin, line); ss << line; int x, y, z; //extract x, y, z and any overflow characters ss >> x >> y >> z >> line; ss.clear(); //reuse ss after clearing the eof flag getline(cin, line); ss << line; //extract new fields, then clear, then reuse //... return 0; }
Depending on the length of each line of input, getting the entire line at a time and processing it in memory is probably more efficient than doing console I / O on each marker that you want to extract from standard input.
source share