C++ 将文件读入数据结构

C++ 将文件读入数据结构,c++,fstream,C++,Fstream,我有一些示例代码,但我不明白为什么它不能正确读取每一行。逻辑看起来不错,但我怀疑在我将文件读入num_of_shades之后,我的file对象中可能存在缓冲区问题 颜色。cpp #include <iostream> #include <fstream> using namespace std; // holds data for my color(s) struct Color { char color_name[255]; // up to 255 char

我有一些示例代码,但我不明白为什么它不能正确读取每一行。逻辑看起来不错,但我怀疑在我将文件读入num_of_shades之后,我的file对象中可能存在缓冲区问题

颜色。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
}
/a.out(程序如何打印)


您正在混合上游提取操作符
>
getline
>
将读取最多个字符,但不包括空格(包括换行符)
getline
将读取整行并丢弃换行符

现在的情况是,换行符是用第一个
getline
读取的。因此,在阴影的输出中可以看到空白行。为了解决这个问题,我将在
文件>>b.color[I].num\u of\u shades

file.ignore(std::numeric_limits<streamsize>::max(), '\n');
file.ignore(std::numeric_limits::max(),'\n');
这将忽略读取数字后剩余的所有内容和换行符

另一个问题是,由于您正在为(j=0;j,因此您阅读的阴影数量比您拥有的阴影数量少了一个。您需要将此更改为:

for (j = 0; j < b.color[i].num_of_shades; j++) 
for(j=0;j
您将希望通过读取本身查看对读取循环的控制,例如,
while(file.getline(b.color[i].color\u name,255)&&file>>b.color[i].num\u色度){…}
然后调用
file.ignore(…)
file.ignore(std::numeric_limits<streamsize>::max(), '\n');
for (j = 0; j < b.color[i].num_of_shades; j++)