【问题标题】:Read empty lines C++读取空行 C++
【发布时间】:2021-10-25 04:35:26
【问题描述】:

我无法从输入中读取和区分空行。

这是示例输入:

 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>>空白,但是没有用。

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

谢谢!

【问题讨论】:

  • 您可以从cin 中读取序列,对吗?因为它忽略了所有的空格。所以没有必要读空格。

标签: c++ input


【解决方案1】:

读完这行的数字后:

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

【讨论】:

  • 不是因为 getLine() 在看到空白字符时停止。所以第一个 getLine() 将消耗空白字符,第二个 getLine() 将消耗空白行。给出的解决方案无论如何都是正确的。
  • 为什么连续提示输入数字不会导致cin 错误;只有在最后一个之后,一个空字符串传递给下一个cin?比如我连续三次cin >> n,那么cin >> string,字符串就会为空,但是之前的cins并没有触发失败
猜你喜欢
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
相关资源
最近更新 更多