The insertion operator >> stops at the first space. use getline() to get a whole sentence.
getline(cin,word);
Ancient Dragon
Retired & Loving It
30,050 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
>can i use strtok to token the string
I wouldn't, use some fancy c++ command. Leave 'C' commands where they belong in 'C'.
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
>can i use strtok to token the string
Not without first copying the string to an array. The c_str member function gives you a pointer to const char, and strtok modifies the string you pass to it. To do it right, you would end up with something like this:
char *tstr = new char[line.size() + 1];
char *tok;
std::strcpy ( tstr, line.c_str() );
tok = std::strtok ( tstr, delim );
while ( tok != 0 ) {
// Process tok
tok = std::strtok ( tstr, 0 );
}
There are better ways than resorting to the C library.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
you can use std::string's find method to locate the spaces
int main()
{
std::string line = "Hello World";
std::string word;
int pos;
while( line != "")
{
pos = line.find(' ');
if(pos >= 0)
{
word = line.substr(0,pos);
line = line.substr(pos+1);
}
else
{
word = line;
line = "";
}
// now word is just one word
cout << word << endl;
}
}
Ancient Dragon
Retired & Loving It
30,050 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
>but how do i want to compare each token in string with word in text file in c++?
How do you define a token? If it's nothing more than a whitespace delimited sequence of characters, the >> operator may be better suited to your problem because it tokenizes input in such a way by default. Why have a two step process (read a line, then tokenize it) when you have a one step process (read a sequence of words)?
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401