簡體   English   中英

從文件輸入不同類型的數據,不使用向量

[英]Input data of different types from a file and NOT USING VECTORS

首先,我是 C++ 的新手,所以不要因為我不知道某些事情或不正確而標記我。 我有一個文件,我試圖將其讀入我的 C++ 程序。 我正在做一個項目的練習。 我必須創建和對象,每個實例代表包含七個變量的文件的一行。 該文件包含一個數據庫。 文本文件的格式為:

// String String Character Int Int Char Int 
// String String Character Int Int Char Int
// etc. 

正好有 350 個數據成員。 再也沒有了。 所以我正在使用數組。 我不能在這個項目中使用向量,因為它被指定不使用。

僅使用數組來解決這個問題的最佳方法是什么?

我的第一次嘗試是創建一個 3 個數組:

        for (int l = 0; l < max_size; l++) {
            myfile >> myintarray[l];
        }
        for (int k = 0; k < max_size; k++) {
            myfile >> mychararray[k];
        }
       for (int i = 0; i < max_size; i++) {
            myfile >> myarray[i];
            // print artists and title; 
        }

       // Then I have to put it the object. Store as such....
        myloop = 0;
        a = 2;
        b = 5;
        while (myloop < 50) {
            myartwork[myloop].setRoom(mychararray[b]);
            myartwork[myloop].myart.setMeduim(mychararray[a]);
            a += 7;
            b += 7;
            myloop += 1;
        }
       // more code where I do the same thing with characters
       // same things with strings.....

當我嘗試它時,它打印了內容。 這是不正確的。 和笨蛋。 所以我認為這是因為當我嘗試存儲所有數字數組時,它不能接受字符並打印出錯誤? 我不確定這是否正確。

然后我嘗試只使用一個字符串數組,然后將每個字符串轉換為 char 或 int 類型。 這很痛苦,我得到了一個錯誤。 我不知道如何處理字符類型。

            myloop = 0;
            a = 3;
            b = 4;
            c = 6;
            while (myloop < 50) {
                //std::stoi (str_dec,&sz)
                std::string::size_type sz;

                // my object ( instance). data......Try to convert this. 
                myartwork[myloop].mymysize.setLength(std::stoi(myarray[a],  &sz));
                myartwork[myloop].mymysize.setWidth(std::stoi(myarray[b], &sz));
                myartwork[myloop].setPrice(std::stoi(myarray[c], &sz));
                a += 7;
                b += 7;
                c += 7;
                myloop += 1;
            }

有沒有比這兩種方法更好的方法呢? 我在正確的軌道上嗎?

使用許多具有相同容量的陣列通常是設計不佳的標志。

讓我們在這里談談建模。 讓我們將記錄定義為字段的容器。 該記錄將與您文件中的一個文本行相對應。 所以,建模:

struct Record
{
    std::string s1;
    std::string s2;
    char        c1;
    int         i1;
    int         i2;
    char        c1;
    int         i3;
};

現在您可以聲明一個表或一記錄:

#define MAXIMUM_RECORDS (350)
Record database[MAXIMUM_RECORDS];

還有一些事情要做:

  1. 重載operator >>以從輸入文件中讀取。
  2. 實現構造函數、復制構造函數和賦值運算符。
  3. 重載比較運算符: ==>等。
  4. 重載operator <<以打印記錄。

暫無
暫無

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

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