-2

I have create a .txt file, which contain a list of product name, description and quantity. For example, like:

100 Plus , Sports Drink , 12 Sprite , Citrus Drink , 5 Dutch Lady, Milk, 8

I want to assign these information to three variable, which is string name, string description, and int quantity

I have tried to use something like while(product >> name >> description >> quantity), but it only works if it contain only single words and without the comma, but not for string with multiple words.

This is my code.

#include <string>
include <fstream>
include <iostream>

using namespace std;

int main()
{
string name, description;
int quantity;
fstream product("product.txt");

string c_name[5],c_description[5];
int c_quantity[5];
int i=0;

while(product  >> name >> description >> quantity)
{

    cout<<i<<" Name= "<<name<<", Description= "<< description <<" , Quantity= " <<quantity<<"\n";
    c_name[i] = name;
    c_description[i] = description;
    c_quantity[i] = quantity;
    i++;
}

cout<<"-------------------------------------------------------------------"<<endl<<endl;

for(i=0;i<5;i++) //to display the variables
{
    cout<<i+1<<" "<<c_name[i]<<endl;
    cout<<i+1<<" "<<c_description[i]<<endl;
    cout<<i+1<<" "<<c_quantity[i]<<endl<<endl;
}

product.close();
return 0;
}

May I know how can I do this? And if possible i'd like to stick with some simple header files only. Thank you very much.

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • What you need is call "parsing" or "tokenizing" : read a line and then use some algorithm to decompose it into the pieces you want. Your parsing is not so difficult because your data format use commas as separators, I can suggest you to have a look at http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c – Jean-Baptiste Yunès Dec 06 '14 at 14:05

2 Answers2

0

You may consider getline() which allows for a delimiter to be used:

while ( getline(getline (product, name, ','), description, ',') >> quantity) 

Just be aware that you may have to remove white spaces at the beining of description and name, as >> was doing it before. Alternatively you may also opt for adding product.ignore(INT_MAX, '\n'); at the end of your loop block, to make sure that the last newline behind quantity is removed before the nex getline is performed.

Christophe
  • 68,716
  • 7
  • 72
  • 138
0

You cannot use stream >> operator because as you found it stops at first whitespace.

You need to read one line at a time with

std::string line;
std::getline(product, line);

and the look for commas with std::string::find and extract the parts you need with std::string::substr.

6502
  • 112,025
  • 15
  • 165
  • 265