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.
You may consider
getline()
which allows for a delimiter to be used:Just be aware that you may have to remove white spaces at the beining of
description
andname
, as>>
was doing it before. Alternatively you may also opt for addingproduct.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.