getline not getting a line!

hi guys,

I've finished my first year in a computing degree and I'm trying to get myself ahead of the game by learning some C++.

I'm having some trouble making getline work in the desired way. At the moment I'm doing little more then asking the user to input an int and then 2 strings however the program seems to be passing over the first getline in my code completly. I'm programming on Microsoft Visual Studio 2008.

Here's my source code

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

int main()
{
int myInt = 0;
cout << "enter integer" << endl;
cin >> myInt;
cout <<"myInt = " << myInt << endl;

string firstString;
cout << "enter string" << endl;
getline(cin,firstString);
cout << "firstString = " << firstString << endl;

string secondString;
cout << "enter string" << endl;
getline(cin,secondString);
cout << "secondString = " << secondString << endl;

system("PAUSE");
return 0;
}

if anyone can explain what's causing the problem I'd be very greatful

Cheers guys
Last edited on
The input stream has an Enter from the previous cin and it doesn't stop for the getline(). Try using a cin.ignore() before the first getline() to clear it.
Yep. I have this same problem a few times. So irritating. Just put like Mitsakos said cin.ignore(); right on top of the firststring declaration.

Or you can change it to using <sstream>.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
  string mystring;
  int input(0);

  cout << "Enter an integer: ";
  getline (cin,mystring);
  stringstream(mystring) >> input;
  cout << input << endl; 
  
  cout << "Enter a string: ";
  getline (cin,mystring);
  cout << mystring << endl;

  cout << "Enter a second string: "; 
  getline (cin,mystring); 
  cout << mystring << endl; 
  
  return 0;
}
Thanks
You guys are legends the lot of ya!

I'm going through this book "learn C++ by making games" already found one problem as it asks you to make a program with strings without putting the #include <string> at the beginning... good start eh?

Anyhow thanks for this, I shall try it once I get home tonight.
Topic archived. No new replies allowed.