getline error?

What is up with this? When I try to get the line as soon as I press a key it stops? Why is that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;

int main ()
{
    cout << "Username:"<<endl;
    string n;
    cin >> n;
    cout << "Hello " << n << endl;
    cout << "Your question?" << endl;
  string str;
  getline (cin,str);
    cout << str << endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;

int main ()
{
    string n;
    cout << "Username:"<<endl;    
    getline (cin, n);
    cout << "Hello " << n << endl;
    cout << "Your question?" << endl;
    string str;
    getline (cin,str);
    cout << str << endl;    
}

try this. it works. Umm getline and cin dont fit together. Wait for the experts for detailed explanation. But, as I know cin.ignore(); should be added after each cin so we can use getline and cin together. For some reason it skips a line. But just used getline for everything now.
However, if you need to cin a int then that might be a problem. So just do cin.ignore();
Last edited on
Yeah I tried that and it works. Thanks ;) How would I save a calculation as a variable? Like say (p * q) // need to convert that to a variable
Last edited on
To put (p * q) into one variable you can just do

int x = (p * q);
and x will store whatever the solution between them is.
Umm getline and cin dont fit together


I believe for cin which is istream class the default delimiter is a whitespace so if you have a whitespace in your input string, they are discarded. For getline, the default delimiter is a newline which means it break upon newline which correspond to the Enter/Return key you enter to terminate your input.
Topic archived. No new replies allowed.