cannot read white spaces

hi everyone , i have to read a text file containing 2 columns , 1 is sort of the instruction and 2nd is the string involced. so i used istringstream for that and it worked fine. the problem is it only read the first words. can someone please help to explain to me . below is the sample of the text file

1
2
3
4
  apple this is sweet
  banana yellow
  orange buy from market
  apple red


it can successfully read the 2nd column but only the first word, not the succeeding
@paulpv278,
Could you have another look at your post. Your sample text file doesn't seem to bear much resemblance to your statement of the problem.

Also, if it can "successfully read the 2nd column", what do you mean by "only the first word"?

If you mean: "read one item, then the rest of the line", then you can use a cin, followed by a getline (and you wouldn't need a stringstream).

Please show your code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
   string item, description;
   ifstream in( "sample.txt" );
   while ( in >> item >> ws && getline( in, description ) )
   {
      cout << "Item: " << item << '\n'
           << "Description: [" << description << "]\n"
           << "---------\n";
   }
   in.close();
}

Item: apple
Description: [this is sweet]
---------
Item: banana
Description: [yellow]
---------
Item: orange
Description: [buy from market]
---------
Item: apple
Description: [red]
---------
Last edited on
sorry to confuse. my sample code is below


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

while(getline( infile,line ))
	{
		istringstream iss(line );
		string columnone="";
		string columntwo="";
	if(iss >>columnone>>columntwo)
	{
		if(instruct=="apple")
		{
		cout<<columntwo<<endl;
		}
		else if(instruct=="banana")
		{
		cout<<columntwo<<endl;
		}
         }
   




now my output is

1
2
this
yellow


but i wanted my output to become
1
2
this is sweet
yellow



means that for the 2nd column, those items with more than 1 word only can read the 1st word
Please consider what I have done in my example:
in >> item >> ws (which gets the first word into the string variable item, and skips the next whitespace)
followed by
getline( in, description ) (which puts the rest of the line into the string variable description).

This should meet your needs. How you output item and description afterwards is entirely up to you.

You don't need a stringstream at all.
Last edited on
Topic archived. No new replies allowed.