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
4.3k views
in Technique[技术] by (71.8m points)

c++ - Why does using two getline function together, second one doesn't take the character?

#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".


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

1 Answer

0 votes
by (71.8m points)

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>?


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

...