如何将文本文件中的数据插入到struct数组中

时间:2011-12-03 02:08:44

标签: c++

我需要从文本文件中读取数据,并将数据插入到struct数组中。数据文件采用以下格式:

productname  price  quantity

我主要关注的是阅读产品名称,其中包含一个和两个单词。我应该将产品名称作为c-string或字符串文字来处理?

任何帮助表示赞赏

#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;
}

1 个答案:

答案 0 :(得分:3)

既然你要求“任何帮助”,这就是我的观点:忘记你写的所有内容,并使用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
        }
    }
}

例如,您可以将每行数据存储在std::tuple<std::string, int, double>中,然后将其放入std::vector