Wizard
Wizard

Reputation: 11265

cin>> not work with getline()

#include <iostream>
#include <string>
using namespace std;

int main () {
  string str;
  int age;
  cout << "Please enter age: ";
  cin>>age;
  cout << "Please enter full name: ";
  getline (cin,str);
  cout << "Thank you, " << str << ".\n";
}

Why function getline() not work when I using uperator >> to input integer ? What is better use for int input ?

Upvotes: -1

Views: 2416

Answers (2)

Bajinga
Bajinga

Reputation: 27

getline() won't work with an int, or any number for that matter. It is defined as such:

istream& getline (char* s, streamsize n );

istream& getline (char* s, streamsize n, char delim );

So, it takes in strings and char*'s; not digits.

Upvotes: 1

Fred Larson
Fred Larson

Reputation: 62053

You still have a newline in the stream after cin>>age;, which is giving you an empty string for the name.

You could solve it by just adding another getline() call after getting the age and throwing away the result. Another options is to call cin.ignore(BIG_NUMBER, '\n');, where BIG_NUMBER is MAX_INT or something.

Upvotes: 5

Related Questions