- 1
Hi
how can I get multiple words in a string ?
When I use cin >> string;
it just stores first word!
I also use getline();
, but it didn't work correctly!
Hello,
You can use cin.getline
. The important thing for using it is you have to pay attention to cursor position.
Say you want to read an integer and then read a whole line:
5
aaaa bbbb cccc
dddd eeee
Imagin we have a cursor here that we show it by ^
character.
^5
aaaa bbbb cccc
dddd eeee
When you read the first integer using int a; cin >> a
, it reads the integer and moves the cursor.
5^
aaaa bbbb cccc
dddd eeee
No, after doing a string str; getline(cin, str)
the function reads everything after the cursor till it reachs \n
. In this case it reads nothing, and moves the cursor to after \n
.
5
^aaaa bbbb cccc
dddd eeee
Now, if you do a getline(cin, str)
, it'll read the whole line and moves the cursur to the beggining of the next line.
5
aaaa bbbb cccc
^dddd eeee
TL; DR
You should read an integer and all the following line, this way:
int a; string str;
cin >> a;
getline(cin, str); // reads nothing, but moves the cursor,
// or you can use anything that reads only one character to move the cursor
while (getline(cin, str)) {
// str contains the whole line
}
if you have a cin
before getline()
you shoude write getchar()
after cin
the library of getchar()
is stdio.h
you should write like this:
cin >> n;
getchar();
getline(cin,str);
Thank you guys for giving your precious time ;-)
Thank you guys for taking your precious time ;-)
In order to post something you must login first. You can use the form in the top of this page.