It doesn't get my line!

I wrote a program using the simple commands based on my brothers request. However, when I compile it, the program ignored one of my getline commands and proceeded to the cout.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main(){
	cout << "What is your name?";
	string mystr;
	getline (cin, mystr);
	cout << "How old are you?";
	int myint;
	cin>> myint;
	cout << "Hello, " << mystr << "! I happened to be " << myint << "years old too!" << endl;
	cout << "What school are you currently studying in?";
	getline (cin, mystr);	//this line doesn't work!!
	cout << mystr << " is an excellent school, isn't it?" << endl;
	cout << "Anyway, what class are you in?";
	getline (cin, mystr);
	cout << "Sorry, I don't happen to know anyone from "<< mystr << ".";

I can't get it. please help.
If I'm not mistaken cin doesn't extract the endline character. When you get buffered input into myint, it leaves behind a '/n' in the buffer, which the next getline picks up and recognizes as input from the user. Try this:

1
2
3
4
int myint;
cin>> myint;
cin.get();  //will extract the '/n' character.
cout << "Hello, " << mystr << "! I happened to be " << myint << "years old too!" << endl;

it works, thanks!
however does it mean that I have to put a cin.get() everytime after I use cin>> ? I mean is there any way of getting input without this kind of problem arising?
It's the mixing of cin >> with getline which causes the incompatibility. If you are just using one of these, things should be fine. Otherwise, you will need to be aware of newline characters remaining in the input buffer.

An alternative, not necessarily recommended, but possible, is to use getline for all the input, and then convert the string to integer or other type as required, for example using atoi() to convert a string to an integer.
Topic archived. No new replies allowed.