Breaking the String into Tokens
May 16, 2012 at 10:53am UTC
Hi Guys !
I'm get input from the user and then storing it in "s " and then trying make tokens, but it is not working, and after making tokens i'm counting them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
string s;
cout<<"Enter Text: " <<endl;
cin>>s;
cout<<"Entered Text is: " << s <<endl;
istringstream iss(s);
int count = 0;
while (iss){
string sub;
iss>>sub;
cout <<"token " << count + 1 << ": " <<sub <<endl;
count = count + 1;
}
cout<<"Number of tokens " <<count -1 << endl;
}
[b]Out put[/b]
Enter text:
Entered Text is: This is String
token 1: This
token 2:
Number of tokens: 1
The problem is that it ignores the rest of string which is "is string" and only consider first word. and also trying to store the first two words in two different variables
Thanks in advance
Sincere Regards,
Ewa
May 16, 2012 at 10:59am UTC
cin>>s;
This will only read one word. Use std::getline to read the whole word.
getline(cin, s);
May 16, 2012 at 11:11am UTC
Thanks Peter
and how to remove the extra token it is generating
Output
Enter text:
Entered Text is: This is String
token 1: This
token 2: is
token 3: String
token 4:
and store This and is into two different variables?
Kind Regards,
Ewa
May 16, 2012 at 11:19am UTC
You could store the values in a vector (or some other container if you prefer).
May 16, 2012 at 11:20am UTC
Okay Thanks for helping i'll work on that one and may need your help to correct it. i'll try to put it into vectors
Regards,
Ewa
May 16, 2012 at 12:02pm UTC
and how to remove the extra token it is generating
You should read it like so:
1 2 3 4 5
string sub;
while (iss>>sub){
cout <<"token " << count + 1 << ": " <<sub <<endl;
count = count + 1;
}
May 16, 2012 at 12:25pm UTC
Hi Guys !
Thanks to Peter and coder helping, your help was very fruitful, i wouldn't make it without your help
And here is my final code if anyone have the same problem
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
string s;
string sa[20];
cout<<"Enter Text: " <<endl;
getline(cin,s);
cout<<"Entered Text is: " << s <<endl;
istringstream iss(s);
int count = 0;
while (iss){
string sub;
iss>>sub;
if (sub == "" ) // breaking input string into tokens
break ;
cout <<"token " << count << ": " <<sub <<endl;
sa[count]= sub; // putting into array
count = count + 1;
}
cout<<"Number of tokens " <<count << endl<<endl;
for (int i = 0; i<2; i++){ // print first and 2nd number tokens
cout<< i + 1 <<" Element of user input is: " <<sa[i]<<endl;
}
return 0;
}
Regards,
Ewa
Topic archived. No new replies allowed.