读取空行C++

Read empty lines C++

本文关键字:C++ 读取      更新时间:2023-10-16

我在读取和区分输入中的空行时遇到问题。

以下是示例输入:

 number
 string
 string
 string
 ...
 number
 string
 string
 ...

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

我的代码执行以下操作:

  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
    }
  }

我直接尝试过cin>>空白,但没有用。

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

谢谢!

在您读取带有此行的数字后:

while(cin >> n) { //number

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
    }
  }