簡體   English   中英

我正在嘗試從文本文件中讀取並將它們分類為結構的不同成員,但我不知道哪里出了問題

[英]I'm trying to read from a text file and categorize them into different members of structure but i don't know where it went wrong

typedef struct
{
    int isbn_code, year_published, quantity, rack, level_no;
    char author[50], title[100], publisher[50];
    double price;
}DATA;

上面顯示的是我的 typedef 結構。 當我調試時,它只顯示“1.”。 所以這是我的代碼。 請告訴我出了什么問題,我需要做什么才能使其正確執行。 我只是想從文本文件中讀取數據並將它們分類為不同的結構成員。

int file_reader()
{
    DATA d;
    ifstream infile("books.txt", ios::in);
    if (infile.is_open())
    {
        while (!infile.eof())
        {
            for (int row = 1; row < 100; row++)
            {
                cout << row << ". ";
                char line[200];
                cin.ignore();
                cin.getline(line, 200, '\n');

                char* column = strtok(line, ",");

                while(column)
                {
                    cin >> d.isbn_code;
                    column = strtok(NULL, ",");
                    cin.getline(column, 50);
                    strcpy(d.author,column);
                    column = strtok(NULL, ",");
                    cin.getline(column, 100);
                    strcpy(d.title, column);
                    column = strtok(NULL, ",");
                    cin.getline(column, 50);
                    strcpy(d.publisher, column);
                    column = strtok(NULL, ",");
                    cin >> d.year_published;
                    column = strtok(NULL, ",");
                    cin >> d.quantity;
                    column = strtok(NULL, ",");
                    cin >> d.price;
                    column = strtok(NULL, ",");
                    cin >> d.rack;
                    column = strtok(NULL, ",");
                    cin >> d.level_no;
                }
                cout << d.isbn_code << "," << d.author << "," << d.title << "," << d.publisher << "," 
                    << d.year_published << "," << d.quantity << "," << d.price << "," << d.rack << "," << d.level_no;
            } cout << endl;
        } infile.close();
    }
    else
        cout << "File is not open\n";
    return 0;
}

這段代碼是錯誤的

cin >> d.isbn_code;

那是從cin而不是從您的文件中讀取 ISBN 代碼。 可能你想要的是這個

d.isbn_code = atoi(column);

然后在接下來的三行

column = strtok(NULL, ",");
cin.getline(column, 50);
strcpy(d.author,column);

您再次從cin讀取而不是從您的文件中讀取。 我想你是這個意思

column = strtok(NULL, ",");
strcpy(d.author,column);

基本上,您一遍又一遍地犯同樣的錯誤,當您說要從文件中讀取時,您正在從cin讀取。 這就是為什么你的程序什么都不做,它在等你輸入一些東西。

還有其他問題(例如,您的循環都是錯誤的,例如,當您顯然想要很多時,您只有一個 DATA 結構)。 但是先修復輸入,然后再看看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM