首页 文章

需要帮助将.txt文件中的数据读入数组C.

提问于
浏览
0
#include <iostream>
#include <fstream>
#include <string>

struct textbook //Declare struct type
{
    int ISBN;
    string title;
    string author;
    string publisher;
    int quantity;
    double price;
};

// Constants
const int MAX_SIZE = 100;

// Arrays
textbook inventory[MAX_SIZE];

void readInventory()
{
    // Open inventory file
    ifstream inFile("inventory.txt");

    // Check for error
    if (inFile.fail())
    {
        cerr << "Error opening file" << endl;
        exit(1);
    }

    // Loop that reads contents of file into the inventory array.

       pos = 0; //position in the array

       while (

        inFile >> inventory[pos].ISBN
               >> inventory[pos].title
               >> inventory[pos].author 
                   >> inventory[pos].publisher
               >> inventory[pos].quantity 
                   >> inventory[pos].price
          )

    {
        pos++;

    } 

    // Close file 
    inFile.close();

    return;

}

你好,

我需要这个功能的帮助 . 此函数的目标是从txt文件中读取信息并将其读入数组结构中以获取教科书 . 文本文件本身已按正确的循环顺序设置 .

我的问题是,对于 Headers 部分,书的 Headers 可能是多个单词,例如“我的第一本书” . 我知道我必须使用getline将该行作为字符串将其输入到'title ' 数据类型 .

我也错过了一个inFile.ignore(),但我不知道怎么把它放到循环中 .

1 回答

  • -1

    假设输入格式为:

    ISBN title author publisher price quantity price
    

    即,数据成员是行空格分隔的,您可以为 struct textbook 定义 operator>> ,它可能类似于:

    std::istream& operator>> (std::istream& is, textbook& t)
    {
        if (!is) // check input stream status
        {
            return is;
        }
    
        int ISBN;
        std::string title;
        std::string author;
        std::string publisher;
        int quantity;
        double price;
    
        // simple format check
        if (is >> ISBN >> title >> author >> publisher >> quantity >> price)
        {
              // assuming you additionally define a (assignment) constructor  
              t = textbook(ISBN, title, author, publisher, quantity, price);
    
              return is;
        }
    
        return is;
    }
    

    然后阅读您的文件,您只需:

    std::ifstream ifs(...);
    
    std::vector<textbook> books;
    
    textbook b; 
    while (ifs >> b)
    {
         books.push_back(b);
    }
    

    关于 getline() 的使用,请参阅answer .


相关问题