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

Categories

#include <bits/stdc++.h>
using namespace std;

int main(){
    string str1, str2;
    getline(cin, str1);  // aaa
    getline(cin, str2);  // bbb
    cout << str1 << " " << str2;   // aaa bbb
    return 0;
}

Why does the 2nd getline() not take , when I input str1 as "aaa "?
cout should print "aaa" not "aaa bbb".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

From the description of std::getline at cppreference (bolding mine):

...until one of the following occurs...

b) the next available input character is delim, as tested by Traits::eq(c, delim), in which case the delimiter character is extracted from input, but is not appended to str.

So, in your case, the newline characters at the end of each input are extracted from the input stream but not added to the two string variables.


Also, please take a look at this: Why should I not #include <bits/stdc++.h>?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...