i input a sentence " i love eat".how can wanto to get c++ to get a full sentence..

#include <iostream>
#include <string>

using namespace std;
void echo(string message)
{
cout << message << endl;
}
int main()
{

cout << "Enter your word: ";
string word; // place declaration near its use
cin>>word
echo(word);

}

but i only get the first word,,how to get the sentence..
i try to use getline(cin,word) but error show up

i had do like this

#include <iostream>
#include <string>

using namespace std;
void echo(string message)
{
cout << message << endl;
}
int main()
{

cout << "Enter your word: ";
string word;
getline(cin,word,'\n');
echo(word);

}

can i use strtok to token the string

>can i use strtok to token the string

I wouldn't, use some fancy c++ command. Leave 'C' commands where they belong in 'C'.

>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.

but how do i want to compare each token in string with word in text file in c++?

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

}

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

This article has been dead for over six months. Start a new discussion instead.