interpret string input of varying lengths

I am trying to read user input for recipe ingredients which must include a ingredient name, and may include a quantity and a unit. Example: Stone ground flour 2 cups or Sugar 1 Tbsp or Milk. The problem I am having is that the string gets cut off after a space when multiple words are used for the ingredient name. If only a one word name is input, then the code works fine. I have to be able to handle ingredients of varying name lengths however. Any suggestions? Thanks for any help.

1
2
3
4
5
6
7
8
9
10
 cin.ignore();
string line;
getline(cin, line);
istringstream record(line);
string name;
string name2;

int quantity = 0;
string unit;
record>>name>>quantity>>unit; 
Last edited on
1
2
3
4
5
6
7
8
std::vector<std::string> ingredient;
ingredient.reserve( 3 );
std::string word;
while ( record >> word )
{
  ingredient.push_back( word );
}
// ingredient is a list of separate words 
Thanks for the reply. When I use your code however all of the ingredient information, including the quantity and units, gets saved into the vector. I need only the name of the ingredient to be saved in the vector. For example if user wants to add 4 cups of Stone Ground Flour then he would type:

Stone Ground Flour 4 cups

I need just the Stone Ground Flour part to be stored into the vector so that the quantity is read as a float value and then the unit is again read in as a string. Is there a way to do this?

My code:
vector<string> ingredient_name;
ingredient_name.reserve( 3 );
string line;
getline(cin, line);
istringstream record(line);
string word;
while ( record >> word )
{
ingredient_name.push_back( word );
}
int quantity = 0;
string unit;
record>>quantity>>unit;//does not store anything into values
string name = "";

int match =0;
int count = 0;
int counter = 0;
for(int i = 0; i < ingredient_name.size(); i++){
name += ingredient_name[i] + " ";
}
cout<<"name is "<<name<<endl;
inventory.add_ingredient(name, quantity, unit);
The thing is that when all the words are in the vector, you can make decisions like:
"Five words. Let me guess, the last is a unit, the second to last might be a number, and perhaps the first three can be reconcatenated as name."
Or:
"One word only. Prepare the supertanker."
Topic archived. No new replies allowed.