C++ - How do I assign the data from a file to several variable

51 views Asked by At

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.

2

There are 2 answers

0
Christophe On

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.

0
6502 On

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.