我正在尝试读取文本文件中的条目并将其放入类中。文本文件的结构如下:
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/