i need a way to get input on string type which include spaces, and below code is what i have done.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <conio.h>
usingnamespace std;
int main()
{
string name = "";
cout << "Name: ";
cin >> name; // this line plus below line, only obtain one string //
//after space
getline(cin, name); // only this line, no problem
cout << name;
getch();
return 0;
}
my question is:
if before getline(), i have a cin,
my input >> "ab cd ef"
what i obtain >> " cd ef"
first "ab" will not count, why it happened like that? how do i obtain all "ab cd ef", can anyone please help...
if i doesn't put "cin >> name;", it skip "getline()" and continue to next cin, and i can't key in data for name....
this is my problem....
you need to learn more about getline and cin.
cin ignores whitespace and will go input info until first whitespace is detected. getline will go until a deliminating character is reach, by default this character is \n
so if you are using cin and getline together you need to clear the \n after each cin statement or else the getline function will start and first hit the \n char, at which point it ends.
what you enter:
enter your letter: A \n
what is in the cin buffer after cin>>char c;
\n
using std::cin.ignore(); it will remove the first character from the cin buffer, which is the \n.
so now the cin buffer is empty.
then you are free to use a getline().
your corrected code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <string>
int main()
{
string name;
string age;
std::cout << "Age: ";
std::cin >> age;
std::cin.ignore();
cout << "Name: "; getline(cin, name); //prompt this line
cout << age <<","<<name;
return 0; //you did forget this.
}