Stop on empty line during user input (C ++)

I have a file that I need to parse using cin and redirect on the command line. The first, however, many lines consists of two two-local and two lines, then an empty line appears, then additional information. I need to stop reading data on this empty line and switch to different variables, because after that the data will be formatted differently. How can I detect an empty cin line without losing any data? Thanks for the help...

+6
source share
2 answers

Parse it as if you were parsing any file and just keep track of when an empty line occurs:

#include <sstream> #include <fstream> #include <string> int main() { std::ifstream infile("thefile.txt", "rb"); std::string line; while (std::getline(infile, line)) // or std::cin instead of infile { if (line == "") { break; } // this is the exit condition: an empty line double d1, d2; std::string s1, s2; std::istringstream ss(line); if (!(ss >> d1 >> d2 >> s1 >> s2)) { /* error */ } // process d1, d2, s1, s2 } // move on } 
+6
source

I would suggest a combination of getline (for detecting empty strings) and stringstream (for parsing). I can expand this with a working example when I get home from work today.

+2
source

Source: https://habr.com/ru/post/898554/


All Articles