1
#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 \n, when I input str1 as "aaa\n"?
cout should print "aaa" not "aaa bbb".

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jayant Sharma
  • 87
  • 1
  • 7

2 Answers2

3

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

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • I got it, It means the delim character is extracted from the input stream & as it get the delim character it stops and there is no character (in my case "\n") left in the input stream. That's why second getline() also takes input "bbb". – Jayant Sharma Jan 13 '21 at 04:45
3

The 1st std::getline() reads in the aaa AND the line break that follows it, but discards the line break. There is no '\n' character saved in str1.

The 2nd std::getline() then reads in the bbb AND the line break that follows it, but discards the line break. There is no '\n' character saved in str2.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • The line break stores in input stream or not? If yes, then why the second getline( ) does not take it. – Jayant Sharma Jan 13 '21 at 04:41
  • 1
    @JayantSharma as I stated, the first `getline()` reads in the line break from the stream, so it not available for the second `getline()` to read in. – Remy Lebeau Jan 13 '21 at 05:09