1
#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

int main() {
    int i2 = 0;
    double d2 = 0.0;
    string s2;

    cin >> i2;
    cin >> d2;
    getline(cin, s2);

    cout << "Integer = " << i2 << endl;
    cout << "Double = " << d2 << endl;
    cout << "String = " << s2 << endl;
}

I'm trying to give sample input as:

12
3.4
Coding

Expected output:

Integer = 12
Double = 3.4
String = Coding

Actual output

Integer = 12
Double = 3.4
String = 

As shown in the above actual output, after feeding the first two inputs from above and the moment the enter is pressed, it's not accepting the next input that I would like to give.

Venkata Pavan
  • 65
  • 1
  • 4

3 Answers3

2

You have a '\n' in the stream, so getline read the empty line. Write:

cin >> d2:
cin.ignore(); // new line
getline(cin,s2);

UPDATE:

You could use a more sofisticated version:

cin >> d2;
cin.ignore(); // removes separator
while (cin && !meaningful(s2))
  getline(cin,s2);

where you could include some tests in the meaningful() function, for example, include more that white spaces.

EFenix
  • 831
  • 4
  • 11
0

When getline() is called there is unread '\n' at cin, that was left unread after

cin >> d2;

So getline() just reads an empty string.

Sergio
  • 7,657
  • 2
  • 22
  • 45
0

You have an unread newline character so your getline will read an empty line.

while(s2.empty())
{
    getline(cin, s2);
}

solves this problem.

Julian Declercq
  • 1,356
  • 2
  • 14
  • 29