0

I am trying to parse a text file that contains a recipe ingredient list

example:

1 cup sour cream 1 cup oil 1 teaspoon lemon juice 

I am not sure how to seperate the 1 cup and sour cream there will always be only 3 parameters per line.

If I separate it by space then sour cream will count as two parameters.

3
  • Use counter for each line, Once the counter for a line becomes 2, then the rest of the words are the recipe. Commented Sep 23, 2013 at 3:58
  • You can join the third to last elements to get the ingredient name Commented Sep 23, 2013 at 3:58
  • @NJMR how would i go about doing that? My C++ is extremely rusty. Commented Sep 23, 2013 at 4:06

4 Answers 4

2
double quantity; string unit; string ingredient; input_stream >> quantity >> unit; getline(input_stream, ingredient); 

click for demo

Sign up to request clarification or add additional context in comments.

5 Comments

Missing the other optional param, bro. ;)
@jrd1: What optional param? For getline? It's optional, and the default is correct for this case.
My bad, I said it incorrectly: The example lines cited have 3 or 4 words. You're missing support to capture the 4th word.
@jrd1: No, I'm not. getline will get the rest of the words on the line.
I see your point. I was going with the idea that all the words had to be separated. But, you're correct. +1
0

so I'm not entirely sure of what you are asking, but if you're asking how to extract the first number and second word together and the rest separately all you would have to do:

string amount, measurements, recipe; while (!infile.eof()){ infile >> amount; //this will always give you the number infile >> measurements; // this will give the second part(cup,teaspoon) getline(infile,recipe); // this will give you the rest of the line 

1 Comment

Newer use !.eof as loop condition! This will usually read one extra line, making a duplicate of the last read item.
0

The naive C++ way in which I would do it would be by splitting the string into two parts on the second space. And the first part would be the string '1 cup' and the second part would be 'sour cream'. But you should probably use flex for this.

Comments

0
#include<iostream> #include<sstream> #include<fstream> using namespace std; int main() { ifstream in_file("test.txt"); string line; while (getline(in_file, line)) { stringstream ss(line); int quantity; string unit; string ingredient; ss >> quantity; ss >> unit; getline(ss, ingredient); cout << "quantity: " << quantity << endl; cout << "uint: " << unit << endl; cout << "ingredient: " << ingredient << endl; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.