1
#include<iostream>
#include<cstring>
using namespace std;

int main() {
    int t;
    cin >> t;

    string s;
    getline(cin, s);
    cout << s;

    return 0;
}

As soon as I press the enter key after giving input for t, the program terminates as string takes the newline character as input. What can I do? I cannot output something between these two inputs and an enter after t is mandatory.

Mitul Jindal
  • 550
  • 3
  • 14

2 Answers2

2

The Enter key you press to end the input for t is added to the input buffer. So the first input in the buffer seen by getline is the Enter key and it thinks you have given an empty line.

Use the ignore function to skip past the newline:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

You can also use two std::getline calls, and use e.g. std::stoi to convert the input an int. Or put in an std::istringstream and extract using the normal >> operator.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550
1

You may use getline(cin, s) twice. Fist will ignore rest of first line and the second will actually read what you need or better use cin.ignore() with appropriate arguments

RiaD
  • 42,649
  • 10
  • 67
  • 110