0

In this C++ code:

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

int main()
{
    string S;
    getline(cin,S);
    cout<<S;

    return 0;
}

It prints the string with spaces, eg:

Input:

abc def

Output:

abc def

However, in this code:

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

int main()
{
    int n;
    cin>>n;
    string S;
    getline(cin,S);
    cout<<S;

    return 0;
}

It does not print any output, eg:

Input:

1
abc def

Output:

How is that even possible? Please help. Where am I going wrong?

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
Saarthak
  • 159
  • 3
  • 9

1 Answers1

3

You read a number and then a line. Think carefully about what is going on, a newline is not part of a number. So if the input is 123 newline, you read the number 123 and then getline reads the newline. Whatever is on the next line hasn't been read at all.

john
  • 71,156
  • 4
  • 49
  • 68