miatech
miatech

Reputation: 2278

how to insert data from a text file into an array of struct

I need to read data from a text file, and insert the data in an array of struct. The data file is in the following format:

productname  price  quantity

my main concern is to read the product name, which consist of one, and two words. Should I approach product name as a c-string or as a string literal?

any help appreciated

#include <iostream>
#include <fstream>

using namespace std;

const int SIZE = 15; //drink name char size
const int ITEMS = 5; //number of products

struct drinks
{
       char drinkName[SIZE];
       float drinkPrice;
       int drinkQuantity;
};      


int main()
{
    //array to store drinks
    drinks softDrinks[ITEMS];

    //opening file
    ifstream inFile;
    inFile.open("drinks.txt");

    char ch;
    int count = 0; //while loop counter


    if(inFile)
    {
         while(inFile.get(ch))
         {
             //if(isalpha(ch)) { softDrinks[count].drinkName += ch; }
             //if(isdigit(ch)) { softDrinks[count].drinkPrice += ch; }
             cout << ch;

         }
         cout << endl;
         count++;  
    }
    else
    {
        cout << "Error opening file!\n";
        system("pause");
        exit(0);
    }

    system("pause");
    return 0;
}

Upvotes: 1

Views: 3167

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477512

Since you ask for "any help", here's my view: Forget everything you wrote, and use C++:

#include <fstream>   // for std::ifstream
#include <sstream>   // for std::istringstream
#include <string>    // for std::string and std::getline

int main()
{
    std::ifstream infile("thefile.txt");
    std::string line;

    while (std::getline(infile, line))
    {
        std::istringstream iss(line);

        std::string name;
        double price;
        int qty;

        if (iss >> name >> price >> qty)
        {
            std::cout << "Product '" << name << "': " << qty << " units, " << price << " each.\n";
        }
        else
        {
          // error processing that line
        }
    }
}

You could store each line of data in a std::tuple<std::string, int, double>, for example, and then put those into a std::vector as you go along.

Upvotes: 3

Related Questions