开发者

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

I've got a file that I need to parse using cin and a redirect at the command line. The first howeve开发者_如何学Gor 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...


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

}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜