将文件读入数据结构
Reading Files into a Structure of Data
我有一些示例代码,但我无法弄清楚为什么它没有正确读取每一行。逻辑看起来不错,但我怀疑在将文件读入num_of_shades后,我的文件对象中可能存在一些缓冲区问题。
颜色.cpp
#include <iostream>
#include <fstream>
using namespace std;
// holds data for my color(s)
struct Color {
char color_name[255]; // up to 255 characters
int num_of_shades;
char shade[10][255]; // up to 10 shades, 255 characters for each row
};
// holds my Color data structure
struct Box {
Color color[5]; // up to 5 colors
};
int main() {
Box b;
ifstream file;
file.open("colors.dat");
int i=0;
int j=0;
while(!file.eof()) {
// can't have more than 5 colors, (index 0 to 4)
if(i >= 5) {
break;
}
file.getline(b.color[i].color_name, 255);
file >> b.color[i].num_of_shades;
// can't have more than 10 shades
if(b.color[i].num_of_shades > 10) {
break;
}
for(j=0; j < b.color[i].num_of_shades-1; j++) {
file.getline(b.color[i].shade[j], 255);
}
i++;
j=0;
}
file.close();
// Print out results (comments to the right are the results I want)
cout << b.color[0].color_name << endl; // RED
cout << b.color[0].num_of_shades << endl; // 3
cout << b.color[0].shade[0] << endl; // Light Red
cout << b.color[0].shade[1] << endl; // Brick Red
cout << b.color[0].shade[2] << endl; // Dark Red
cout << b.color[1].color_name << endl; // BLUE
cout << b.color[1].num_of_shades << endl; // 2
cout << b.color[1].shade[0] << endl; // Dark Blue
cout << b.color[1].shade[1] << endl; // Light Blue
}
颜色.dat(我的.dat文件的外观,以及我想打印出数据的方式(
RED
3
Light Red
Brick Red
Dark Red
BLUE
2
Dark Blue
Light Blue
./a.out(程序如何打印出来(
Red
3
Light Red
Brick Red
0
您混淆了流提取运算符>>
和getline
。>>
将读取字符,但不包括空格(包括换行符(。getline
将读取整行并丢弃换行符。
正在发生的事情是,换行符与阅读阴影的第一个getline
一起读取。因此,您在阴影输出中看到的空白行。为了解决这个问题,我会在file >> b.color[i].num_of_shades;
之后添加这一行:
file.ignore(std::numeric_limits<streamsize>::max(), 'n');
这将忽略读取数字后剩余的所有内容和换行符。
您遇到的另一个问题是,您正在阅读的阴影数量减少了一个,因为您正在做for(j=0; j < b.color[i].num_of_shades-1; j++)
。您需要将其更改为:
for (j = 0; j < b.color[i].num_of_shades; j++)
相关文章:
- 将文本文件解析为树状数据结构
- 将文件读入数据结构
- 用指向文件的指针存储数据结构
- 将文件目录打印到数据结构中
- 多线程和共享资源:使用C++定期将数据从缓冲区(数据结构)复制到文件
- 是否值得两次通过文件进行迭代,以创建最小的数据结构
- 最佳数据结构存储文本文件中的数字集
- 我需要将数据从文件中读取到结构的向量
- 文件系统中的数据结构存储
- 使用二进制模式将数据结构写入文件
- 要存储到数据结构中的制表符分隔的文件数据
- 将数据从文件加载到C++中的数据结构并对其进行解释
- 将树数据结构转储到文件/从文件还原树数据结构
- 将大数据文件读入数据结构 c++
- 将数据从文件读取到结构中
- 使用字符串函数将数据从文件读入结构
- 如何将数据从文件读取到结构中
- c或c++中是否有头文件来实现图、树等数据结构
- 使用char*和std::list将数据结构写入二进制文件
- 如何在.cpp文件中使用Cuda数据结构