C++ Getline after Cin

会有一股神秘感。 提交于 2019-12-20 03:34:07

问题


I am trying to write a program which gets user's input in a specific way. First, I input a word which contains no space; Then, I input another word which may contains space; And the program outputs the 2 words separately.

For example, I input "Tom a lazy boy" Then the program outputs "Tom:a lazy boy"

Here is what I attempted to do:

int main(){
    string a;
    cin >> a;
    string b;
    getline(cin, b);
    cout << a << ":" << b<< endl;
}

I tried using getline after cin, however the output looks like: "Tom: a lazy boy"

If I input "Tom(many spaces)a lazy boy" then it outputs "Tom:(many spaces)a lazy boy" and I want don't want those spaces. Is there a better way to do this?

I see there are some ways which requires editing the string after cin, but can we solve the problem right at the input stage?


回答1:


The std::getline function does not skip whitespace like the normal input operator >> does. You have to remove leading (and possible trailing?) whitespace yourself.

Removing the leading whitespace can be done by first finding the first non-whitespace character (with e.g. std::find_if) and then get a substring from that position to the rest (with std::string::substr).


Or as dyp suggests, use std::ws. The linked reference have a very good example how to use it.




回答2:


getline() reads whitespaces, if you want to ignore the leading whitespaces try:

cin.ignore();
getline(cin, b);

EDIT: Sorry, this indeed reads 1 character, this is another solution for you:

    getline(cin, b);
    string noLeadingWS = b.substr(b.find_first_not_of(' '),b.length()-b.find_first_not_of(' '));
    cout << a << ": " << noLeadingWS<< std::endl;



回答3:


So it looks like your program is just grabbing the space that you put in the program, you can get rid of it several ways!

  1. You can stream the input yourself using cin.get() character by character you add them into a string until you get a space then keep going but don't add the spaces until you get something that isn't a space, then use your getline or you can continue your custom streaming this time looking for a newline!

  2. You can just edit the resulting string to remove the extra spaces super easily, look at the substr() method!



来源:https://stackoverflow.com/questions/23136487/c-getline-after-cin

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