Using getline() in C++

自闭症网瘾萝莉.ら 提交于 2019-11-26 03:54:55

问题


I have a problem using getline method to get a message that user types, I\'m using something like:

string messageVar;
cout << \"Type your message: \";
getline(cin, messageVar);

However, it\'s not stopping to get the output value, what\'s wrong with this?


回答1:


If you're using getline() after cin >> something, you need to flush the newline character out of the buffer in between. You can do it by using cin.ignore().

It would be something like this:

string messageVar;
cout << "Type your message: ";
cin.ignore(); 
getline(cin, messageVar);

This happens because the >> operator leaves a newline \n character in the input buffer. This may become a problem when you do unformatted input, like getline(), which reads input until a newline character is found. This happening, it will stop reading immediately, because of that \n that was left hanging there in your previous operation.




回答2:


If you only have a single newline in the input, just doing

std::cin.ignore();

will work fine. It reads and discards the next character from the input.

But if you have anything else still in the input, besides the newline (for example, you read one word but the user entered two words), then you have to do

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

See e.g. this reference of the ignore function.

To be even more safe, do the second alternative above in a loop until gcount returns zero.




回答3:


I had similar problems. The one downside is that with cin.ignore(), you have to press enter 1 more time, which messes with the program.




回答4:


int main(){
.... example with file
     //input is a file
    if(input.is_open()){
        cin.ignore(1,'\n'); //it ignores everything after new line
        cin.getline(buffer,255); // save it in buffer
        input<<buffer; //save it in input(it's a file)
        input.close();
    }
}



回答5:


i think you are not pausing the program before it ended so the output you are putting after getting the inpus is not seeing on the screen right?

do:

getchar();

before the end of the program




回答6:


The code is correct. The problem must lie somewhere else. Try the minimalistic example from the std::getline documentation.

main ()
{
    std::string name;

    std::cout << "Please, enter your full name: ";
    std::getline (std::cin,name);
    std::cout << "Hello, " << name << "!\n";

    return 0;
}


来源:https://stackoverflow.com/questions/18786575/using-getline-in-c

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