c++ - 读取 .txt 以构建有限数量的项目

标签 c++ arrays struct

虽然我曾短暂使用过 C# 和一些 Web 开发语言,但我对 C++ 还很陌生。 我有一个数据库作为 .txt 文件存储在已知位置。 .txt 文件的第一行是数据库中有多少项目。 我有一个结构来读取所有值,因为它们具有相同的格式。

我已经设法写了一段代码,它会读入文件并给我一个整数值,表示有多少项目,我只需要帮助将数据读入结构数组。

一个示例数据库是

3

NIKEAIRS
9
36.99

CONVERSE
12
35.20

GIFT
100
0.1

我的结构是

struct Shoes{
   char Name[25];
   unsigned int Stock;
   double Price;
};

我读取项目数量的代码是

#include <iostream>
#include <fstream>
#include <string>
using namespace std;


int main ()
{
    char UserInput;

    string NumOfItems; //this will contain the data read from the file
    ifstream Database("database.txt"); //opening the file.
    if (Database.is_open()) //if the file is open
    {
        int numlines;
        getline (Database,NumOfItems);
        numlines=atoi(NumOfItems.c_str());
        cout<<numlines;
    }
    else cout << "Unable to open file"; //if the file is not open output
    cin>>UserInput;
    return 0;
}

我能否就如何进行提供一些指示。

最佳答案

这样的事情怎么样?我知道有更有效的方法可以做到这一点, 但至少这应该让你开始朝着正确的方向前进。干杯!

#include <iostream>
#include <fstream>
#include <string>

#include <vector>
#include <stdlib.h>

using namespace std;

struct Shoes {
    char Name[25];
    unsigned int Stock;
    double Price;
};

vector<Shoes> ShoeList;

static Shoes readShoe(std::ifstream& fs)
{
    char buffer[200];               //  temporary buffer
    Shoes s;

    fs.getline(buffer, sizeof(buffer));     // newline
    fs.getline(s.Name, sizeof(buffer));     // name
    fs.getline(buffer, sizeof(buffer));     // amt in stock
    s.Stock=atoi(buffer);
    fs.getline(buffer, sizeof(buffer));     // price
    s.Price=strtod(buffer, 0);

    return s;
}

int main ()
{
    char UserInput;

    string NumOfItems; //this will contain the data read from the file
    ifstream Database("database.txt"); //opening the file.
    if (Database.is_open()) //if the file is open
    {
        int numlines;
        getline (Database,NumOfItems);
        numlines=atoi(NumOfItems.c_str());
        cout<<numlines;

    cout << endl;
    for(int i=0; i < numlines; ++i)
    {
        Shoes s = readShoe(Database);
        ShoeList.push_back(s);
        cout << "Added (Name=" << s.Name << "," << s.Stock << "," << s.Price << ") to list." << endl;
    }

    }
    else cout << "Unable to open file"; //if the file is not open output

    cin>>UserInput;

    return 0;
}

关于c++ - 读取 .txt 以构建有限数量的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13332899/

相关文章:

java - 我可以检查是否返回了 void 方法吗?

android - 有没有办法在 C++ 中以编程方式执行 adb 命令?这部分 C++ 代码是使用 android studio 中的 ndk build 构建的。那里

c++ - 在 windows eclipse 中使用 DGEMM BLAS

.net - C++/CLI 能否用于从 native C++ 应用程序调用 .NET 代码?

arrays - 比较一个对象看它是否是一个集合而不使用 TypeName 并将其作为字符串进行比较?

javascript - 闭包、递归和 settimeout - 记录空数组

从 void* 转换为 struct

c++ - 无法将 {...} 从 <brace-enclosed initializer list> 转换为 struct

c++ - SolFS 中这些函数的等价物?

struct - 比结构方法长寿