c++ - 将文件读入数据结构
问题描述
我有一些示例代码,但我无法弄清楚为什么它没有正确读取每一行。逻辑看起来不错,但我怀疑在我将文件读入 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
}
colors.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# 泛型调用
- jquery - 选择 n 个选项时使用 jquery 追加和删除 div
- hl7-fhir - 如何使用 FhirDotNet 获取相同类型的两个资源之间不同的属性列表
- javascript - 连续的承诺调用覆盖返回值
- javascript - 在 protractor.conf.js 中找不到模块浏览器?
- ios - 在横向模式下隐藏菜单页面 iPad 主详细信息页面
- swift - 添加孩子时的Firebase,另一个孩子被删除
- java - 在 Rational 类中相互调用方法
- r - 当需要其他参数时,如何避免使用 for 循环?
- python - 通过 GET 发送时发送到 django 表单的请求对象正常,但通过 POST 发送时为空