Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

space - C++ Getline after Cin

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...