【问题标题】:Read from mixed data file add items to string array and two-dimensional int array C++ [closed]从混合数据文件中读取将项目添加到字符串数组和二维 int 数组 C++ [关闭]
【发布时间】:2018-11-24 17:30:10
【问题描述】:

我有一个如下所示的文本文件:

    January 35 45 
    February 45 55 
    etc...

我正在尝试通读该文件并将每个月添加到一个字符串数组中,然后将每个后续整数添加到一个二维数组中。

我有一个months[] 数组和一个temps[][] 数组。

我正在尝试这样的事情

int size = 0;
while(!file.eof()) {
    file >> months[size];
    size++;
}

我不知道如何将两个整数添加到 int 数组中......

这是给一个类,惊喜惊喜,具体要求是从文件中读取数据,将月份插入到数组中,后面的两个整数插入到二维数组中。

我们还没有讨论过结构或向量。

【问题讨论】:

标签: c++ arrays


【解决方案1】:

不要使用数组。具有结构的模型。

struct Month_Record
{
  std::string month_name;
  int         value_1;
  int         value_2;
};

接下来,添加一个输入结构的方法:

struct Month_Record
{
  //... same as above
  friend std::istream& operator>>(std::istream& input, Month_Record& mr);
}

std::istream& operator>>(std::istream& input, Month_Record& mr)
{
  input >> mr.month_name;
  input >> mr.value_1;
  input >> mr.value_2;
  return input;
}

你的输入变成:

std::vector<Month_Record> database;
Month_Record mr;
while (input_file >> mr)
{
  database.push_back(mr);
}

你可以像数组一样访问数据库:

std::cout << database[0].month_name 
          << ", " << database[0].value_1
          << ", " << database[0].value_2
          << "\n";

该模型的一个不错的功能是您可以将记录放在一个缓存行中。对于并行阵列,处理器可能必须重新加载数据缓存以从其他阵列获取数据(因为可能必须将整个阵列加载到缓存中)。

【讨论】:

  • 这是一个类,要求具体使用并行数组和二维数组。
  • @BenGrzybowski 做你必须做的事情来通过课程,但这是做这项工作的正确方法。
【解决方案2】:
int size = 0;
while(size < MAX_ARRAY_LENGTH && // prevent overflow. 
                                 // Will stop here if out of space in array
                                 // otherwise && (logical AND) will require the following be true 
      file >> months[size] // read in month 
           >> temps[size][0] // read in first temp
           >> temps[size][1]) // read in second temp 
{ // if the month and both temperatures were successfully read, enter the loop
    size++;
}

MAX_ARRAY_LENGTH 是一个常数,定义了可以放入数组的最大月数。

&gt;&gt; 返回对正在读取的流的引用,因此您可以将操作链接在一起,并在完成读取时利用流的operator bool。如果流仍处于良好状态,operator bool 将返回 true。

逻辑看起来像

loop
if array has room
    read all required data from stream
    if all data read
        increment size
        go to loop.

您可能需要在循环结束后进行测试,以确保读取了所有数据。如果您正在阅读文件末尾,if (file.eof()) 之类的内容将确保已读取整个文件。如果您想要一年的数据,if (size == ONE_YEAR) 其中ONE_YEAR 是定义一年中月数的常量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多