Can anybody please tell me what is wrong with this piece of code?

std::string query;
	std::cout << "Enter the Query String :";// Type something with spaces here. e.g ( "financial instruments being traded on the American stock exchange" );
	while (std::cin >> query )
	{
		std::cout << query <<std::endl;
	}

The objective is to tokenize the string at whitespace as it is read from cin.
e.g the output should be

Enter the Query String :financial instruments being traded on the American stock exchange
financial
instruments
being
traded
on
the
American
stock
exchange

What is the problem you are facing...I am getting the desired output.

commented: Thanks for taking the time to look at this +1

Thanks for looking in to it.
I get the output. But after printing the last word, it just hangs like as if expecting another string too. I tried running it under a debugger and had a look at the contents of query . I couldn't see the values, only "badptr".

My environment is
Operating System Windows XP.
Compiler Visual C++ Express 2005

>But after printing the last word, it just hangs like as if expecting another string too.
Probably because it's expecting another string. A newline is whitespace too, and unless you're terminating the loop with Ctrl+Z (or a read error occurs), it'll just keep asking you for another string. If you want to simply type the line and have the program "do the right thing", you shouldn't use cin's >> operator. Instead, a combination of getline and stringstream will do what you want:

if ( getline ( std::cin, query ) ) {
  std::stringstream ss ( query );
  std::string token;

  while ( ss>> token )
    std::cout<< token <<'\n';
}
commented: ��も�り��������。 +1

Thank you very much. That was perfect.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.