【问题标题】:c++ getline doesn't get the inputc ++ getline没有得到输入
【发布时间】:2015-11-30 02:34:02
【问题描述】:

我正在尝试输入一行,然后输入一个整数,然后再输入一行,但是当最后一个 cin 获取该行并且我按 Enter 时,它会崩溃或随机输出到无穷大。怎么了?

int main(){
    string a= "", b = "";
    int n1 = 0, n2 = 0;

    getline(cin, a);
    cin >> n1;

    //when i input the next like it outputs randomly without continuing with the next like why?
    getline(cin, b);

    //it doesn't let me to input here coz it's outputting some random strings.
    cin >> n2;
    return 0;
}

感谢您的帮助,谢谢。

【问题讨论】:

  • it crashes or outputs randomly 我感觉你没有显示你正在使用的代码,因为上面的代码不可能崩溃甚至输出。在任何情况下,getline(cin, b); 并没有按照您的想法执行,您的缓冲区中可能有一个从cin >> n1; 遗留下来的换行符,所以getline(cin, b); 读取该换行符,然后cin >> n2; 尝试读取您期望的任何内容被读入b 并且可能会失败。
  • 不要将getlinecin >> 类型输入混用。它永远不会像你期望的那样工作。
  • 它实际上并没有崩溃,而是输出随机文本。
  • 对于这类问题,您应该复制并粘贴您的确切输入,因为您的代码将“工作”某些输入而不是其他输入。

标签: c++ codeblocks cin getline


【解决方案1】:

您需要使用换行符。

int main(){
    string a, b;
    int n1, n2;

    getline(cin, a);

    cin >> n1;
    cin.get(); // this will consume the newline
    getline(cin, b);

    cin >> n2;
    cin.get(); // this will consume the newline
}

std::getline 将为您使用换行符。

以下是示例用法:

21:42 $ cat test.cc 
#include <iostream>
#include <string>

using namespace std;

int main(){
    string a, b;
    int n1, n2;

    getline(cin, a);

    cin >> n1;
    cin.get(); // this will consume the newline
    getline(cin, b);

    cin >> n2;
    cin.get(); // this will consume the newline

    std::cout << a << " " << b << " " << n1 << n2 << std::endl;
}
✔ ~ 
21:42 $ g++ test.cc
✔ ~ 
21:42 $ ./a.out 
hello
4
world
2
hello world 42

【讨论】:

  • 谢谢,之前我不使用 c++,我忘记了 cin.get()。谢谢你兄弟。
  • get 可能有问题......它只读取一个字符,因此如果数字后有任何尾随空格,那么您将不会按预期使用“换行符”。 Walt 建议使用ignore 更可靠,尽管忽略输入也很危险:使用skipws 然后检查下一个字符是换行符更可靠。 OP 的代码没有做任何错误检查,所以基准测试很低。
  • 我倾向于专门使用 getline,但他想知道它不起作用的原因。
  • 我不知道我可以输入数字而不将它们视为字符串。但是,当我使用忽略时,它忽略了下一个 cin。为什么会发生@TonyD?
  • @kobbycoder:没有看到您的实际输入并尝试使用忽略,很难说。工作版本可用here 供参考/比较。
【解决方案2】:

对于cin 之后的情况,您应该使用cin.ignore() 而不是cin.get(),如下所示:

cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\n');

【讨论】:

  • 我之前使用过忽略,但它跳过了第三个 cin
猜你喜欢
  • 2018-03-17
  • 2021-12-21
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 2012-09-21
相关资源
最近更新 更多