c - 将 FILE * 读入类中

标签 c file class

我正在尝试读取文本文件中的条目并将其放入类中。文本文件的结构如下:

ABCD
3.00
2
6.00
-

进入类(class):

typedef struct item
{
    char        *name;
    double      uprc;
    double      cost;
    int         qty;
} item;

“ABCD”是名称,3.00 是 uprc,2 是 qty,6.00 是 cost

我该如何实现这个?到目前为止,我已经:

void read()
{
    item i;
    FILE *f = fopen(PATH, "r");
    char *buf;
    int c, nl_ct = 0;
    while((c = getch(f)) != EOF){
        putchar(c);
        if(c == '\n'){
            nl_ct++;
            switch(nl_ct){
            case 1:
                {
                    char *buf;
                    while(fgets(buf, sizeof(buf), f))

                }
                break;
            }
        }
    }
}

但是,我不知道在最里面的 while 循环中要做什么。另外,这段代码看起来不正确。

我该如何编码?

最佳答案

如果您只使用 C++ 提供的工具,这会变得更加简单。

给定:

class item
{
public:
    std::string name;
    double uprc;
    double cost;
    int qty;
};

您可以这样做(在包含 <string><fstream><iostream> 后):

std::ifstream input(PATH);
item i;

std::getline(input, i.name); 
input >> i.uprc;
input >> i.qty;
input >> i.cost;

使用std::getline的原因如果你这样做 input >> i.name; ,那么整行都会被读取那么它只会读取到第一个空白字符,因此它不适用于带有空格的名称。

或者,您可以提供自己的 operator>>这样你就可以做 input >> i; 。另请注意,此处没有进行错误检查,因此您需要自己添加。

关于c - 将 FILE * 读入类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24521180/

相关文章:

c# - 没有实现的 C# 类如何有效?

c - 这两个指针有何不同?

c++ - VS 2010下编译C代码

objective-c - 如何将 NSString 转换为对象 C 中的 char[] 数组

python - 从文件和 os.listdir python 构建字典

Android - 单独类中的 OnClick 监听器

java - 为每个 POST 和接收使用两个相同的类 - REST

c - 当缓冲区太小无法容纳一些数据时会发生什么

Python:循环读取所有文本文件行

ruby-on-rails - 在Ruby on Rails中复制文件