-3

The contents of menu.txt are:

1 Fish Dish:Fish and chips  

And my code is:

int itemNo;
string category;
string descript;

ifstream infile("menu.txt"); 
infile >> itemNo >> category >> descript;
cout << category  << " - " << descript << " - " << itemNo <<'\n';

I want to get:

Fish Dish - Fish and chips - 1

But for some reason I just get:

Fish - Dish:Fish - 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
bon123
  • 61
  • 1
  • 6
  • `ifstream` uses whitespace as a delimiter by default, "Fish Dish" for example has a space in it. – ricco19 May 07 '18 at 19:35
  • 1
    How is `>> category` supposed know to read until `:`? – Barmar May 07 '18 at 19:38
  • 1
    To change the delimiter, see [this questioin](https://stackoverflow.com/questions/7302996/changing-the-delimiter-for-cin-c). – Beta May 07 '18 at 19:51

1 Answers1

0

You could change the delimiter to be the colon. See this answer for more information

Or the simpler approach would be to use the getline() function:

istream& getline (istream& is, string& str, char delim)

So, for your example:

int itemNo;
string category;
string descript;

ifstream infile("menu.txt");
infile >> itemNo;
getline(infile, category, ':');
getline(infile, descript);
cout << category  << " - " << descript << " - " << itemNo <<'\n';

That will give:

 Fish Dish - Fish and chips - 1

To get rid of the extra space at the start of Fish Dish, add an extra getline.

int itemNo;
string category;
string descript;

ifstream infile("menu.txt");
infile >> itemNo;
getline(infile, category, ' ');
getline(infile, category, ':');
getline(infile, descript);
cout << category  << " - " << descript << " - " << itemNo <<'\n';