Блог пользователя Rainmaker

Автор Rainmaker, 12 лет назад, По-английски

In C++, one can make string handling lot simpler using strings and string steam class.

I used to take a lot of time thinking how we should take the input from the user, at times I needed the whole line to be a part of the string, and there were times when I wished only the characters till the next space would be entered in the string.

So, heres a brief tutorial for me for scanning the whole line/ part of the string from the user.

1. Scanning the whole line:

consider the line you want to scan is:

you are my pumpkin pumpkin, hello honey bunny!

Now, if you just do

string S;
cin >>S ;
cout << S;

you will get just

you

as your output. To get the whole string as an input, use the following line:

string S;
getline(cin,S);
cout << S;

you get the whole line scanned in S.

2. tokenizing the scanned line

using stringstream class would help tokenize the string.

use the following::

 #include<sstream>
 
 stringstream SS;
 string s,s1;
 getline(cin, s);
 SS << s;
 do{
     s1.erase(); // to remove all characters from s1.
     SS >> s1;
 cout << s1 << endl;
 }while(SS);
 
 SS.str("");    // to reuse the stringstream object.

Hope this helps!

Полный текст и комментарии »

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится