std::getline on std::cin

不羁岁月 提交于 2019-11-26 14:49:40

问题


Is there any good reason why:

std::string input;
std::getline(std::cin, input);

the getline call won't wait for user input? Is the state of cin messed up somehow?


回答1:


Most likely you are trying to read a string after reading some other data, say an int.

consider the input:

11
is a prime

if you use the following code:

std::cin>>number;
std::getline(std::cin,input)

the getline will only read the newline after 11 and hence you will get the impression that it's not waiting for user input.

The way to resolve this is to use a dummy getline to consume the new line after the number.




回答2:


I have tested the following code and it worked ok.

#include <iostream>
using namespace std;
int main()
{
    string  input;
    getline(cin, input);
    cout << "You input is: " << input << endl;
    return 0;
}

I guess in your program that you might already have something in you input buffer.




回答3:


This code does not work:

#include <iostream>
#include <string>

int main()
{
int nr;
std::cout << "Number: ";
std::cin >> nr;

std::string  input;
std::cout << "Write something: ";
getline(std::cin, input);
std::cout << "You input is: " << input << std::endl;

return 0;
}

Now it works:

#include <iostream>
#include <string>

int main()
{
int nr;
std::cout << "Number: ";
std::cin >> nr;

std::string x;
std::getline(std::cin,x);

std::string  input;
std::cout << "Write something: ";
getline(std::cin, input);
std::cout << "You input is: " << input << std::endl;

return 0;
}


来源:https://stackoverflow.com/questions/6819082/stdgetline-on-stdcin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!