Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping at Blank Line During User Input (C++)

Tags:

c++

I've got a file that I need to parse using cin and a redirect at the command line. The first however many lines consist of two doubles and two strings, then comes a blank line, then more information. I need to stop reading in the data at this blank line and switch to different variables because the data will be formatted differently after this point. How can I detect a blank line with cin, while not losing any data? Thanks for the help...

like image 864
Max Avatar asked Oct 03 '11 23:10

Max


2 Answers

Parse it like you would parse any file and just keep track of when an empty line happens:

#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

}
like image 175
Kerrek SB Avatar answered Oct 06 '22 00:10

Kerrek SB


I'd suggest a combination of getline (to detect blank lines) and stringstream (for parsing). I can expand on this more with a working example when I get home from work today.

like image 21
K Mehta Avatar answered Oct 06 '22 00:10

K Mehta