繁体   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