while( getline( infile2, temp2 ) )
         
{
         size_t prev_pos = 0, pos = 0;
         
        while( (pos = temp2.find(' ', pos)) != std::string::npos )
         {
        string wordtobold( temp2.substr(prev_pos, pos-prev_pos) );

        cout << wordtobold << '\n';

        prev_pos = ++pos;
    }
       string wordtobold(temp2.substr(prev_pos, pos-prev_pos) ); // Last word
   cout << wordtobold << '\n';  
   
   return 0;

}

i am going to tokenize my string, which is read from a file,
but my output is blank, why?

And i have tried to remove the getline while loop, like this and it gives correct output, why??

string temp2 ("THIS IS A SENTENCE");

         size_t prev_pos = 0, pos = 0;
         
        while( (pos = temp2.find(' ', pos)) != std::string::npos )
         {
        string wordtobold( temp2.substr(prev_pos, pos-prev_pos) );

        cout << wordtobold << '\n';

        prev_pos = ++pos;
    }
       string wordtobold(temp2.substr(prev_pos, pos-prev_pos) ); // Last word
   cout << wordtobold << '\n';  
   
   return 0;

how can i read several line in file and tokenize each line?

Is your output Blank or nonexistant?

Is your output Blank or nonexistant?

the output is nonexistant, sorry for my mistake :)

Why are you specifying a function prototype string wordtobold( temp2.substr(prev_pos, pos-prev_pos) ); instead of calling the function wordtobold( temp2.substr(prev_pos, pos-prev_pos) ); :icon_question:

How do you know the getline() call is returning TRUE?

>> ... tokenize my string, which is read from a file, but my output is blank, why?

There could be many reasons for no output at all - was the file opened, what's in it etc. You could get a bit creative and display what you read from the file ..

while( getline( infile2, temp2 ) )
{
  cout << "read: [" << temp2 << "]" << '\n';
  ...
}

At any rate, in your first snippet, you should remove the return 0; -- it's inside the outer loop.

Other than that, I think you are close to a working solution -- maybe consider how will you want to handle leading/trailing and consecutive space characters.

i just removed the return 0; , but still doesnt work :(...

OH, i read a old post and i found a solution,
for others reference, i just post the code here, and my thread is solved. Thanks everyone!!

std::string temp, total;

while (!file.eof())

{

std::getline(file,temp); // delimeter is the newline char by default

total += temp;

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