← Discussion

string

Na Weed · 2014-12-13 15:16:49

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!

AMiR · 2014-12-13 21:42:15

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
}

Gandom · 2014-12-13 21:59:02

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);

Na Weed · 2014-12-14 19:03:39

Thank you guys for giving your precious time ;-)

Na Weed · 2014-12-14 19:10:29

Thank you guys for taking your precious time ;-)

pages:
  • 1