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.
-
Use counter for each line, Once the counter for a line becomes 2, then the rest of the words are the recipe.user1814023– user18140232013年09月23日 03:58:54 +00:00Commented Sep 23, 2013 at 3:58
-
You can join the third to last elements to get the ingredient namecongusbongus– congusbongus2013年09月23日 03:58:59 +00:00Commented Sep 23, 2013 at 3:58
-
@NJMR how would i go about doing that? My C++ is extremely rusty.clifford.duke– clifford.duke2013年09月23日 04:06:47 +00:00Commented Sep 23, 2013 at 4:06
4 Answers 4
double quantity;
string unit;
string ingredient;
input_stream >> quantity >> unit;
getline(input_stream, ingredient);
5 Comments
getline will get the rest of the words on the line.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
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
#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;
}
}