读空行C++

Lar*_*ite 5 c++ input

我无法读取和区分输入中的空行.

这是示例输入:

 number

 string
 string
 string
 ...

 number

 string
 string
 ...
Run Code Online (Sandbox Code Playgroud)

每个数字代表输入的开始,字符串序列表示输入结束后的空白行.字符串可以是短语,而不仅仅是一个单词.

我的代码执行以下操作:

  int n;

  while(cin >> n) { //number

    string s, blank;
    getline(cin, blank); //reads the blank line

    while (getline(cin, s) && s.length() > 0) { //I've tried !s.empty()
        //do stuff
    }
  }
Run Code Online (Sandbox Code Playgroud)

我已经尝试直接cin >>空白,但它没有用.

有人可以帮我解决这个问题吗?

谢谢!

Ben*_*ley 6

用这一行读取数字后:

while(cin >> n) { //number
Run Code Online (Sandbox Code Playgroud)

cin在最后一位数字后没有读取任何内容.这意味着cin的输入缓冲区仍然包含该数字所在的其余行.所以,你需要跳过那一行,然后是下一个空行.你可以通过两次使用getline来做到这一点.即

while(cin >> n) { //number

    string s, blank;
    getline(cin, blank); // reads the rest of the line that the number was on
    getline(cin, blank); // reads the blank line

    while (getline(cin, s) && !s.empty()) {
        //do stuff
    }
  }
Run Code Online (Sandbox Code Playgroud)