【问题标题】:How to read a text file into parallel arrays如何将文本文件读入并行数组
【发布时间】:2022-08-08 15:47:29
【问题描述】:

我必须有一个从文本文件中读取卡片信息的函数 (cards.txt) 并使用指针将它们插入到主程序中的并行数组中。

我已成功读取文本文件,但无法成功将信息插入数组。

#include <iostream>
#include <stream>
#include <string>
using namespace std;

void readCards();

int main() {
  ifstream inputFile;
  const int SIZE = 10;
  int id[SIZE];
  string beybladeName[SIZE];
  string productCode[SIZE];
  string type[SIZE];
  string plusMode[SIZE];
  string system[SIZE];

  readCards();

  return 0;
}

void readCards() {
  ifstream inputFile;
  const int SIZE = 10;
  int id[SIZE];
  string beybladeName[SIZE];
  string productCode[SIZE];
  string type[SIZE];
  string plusMode[SIZE];
  string system[SIZE];
  int i = 0;

  inputFile.open(\"cards.txt\");
  cout << \"Reading all cards information...\" << endl;
  if (inputFile) {
    while (inputFile >> id[i] >> beybladeName[i] >> productCode[i] >> type[i] >> plusMode[I] >>
      system[I]) {
      i++;
    }
    cout << \"All cards information read.\" << endl;
  }
  inputFile.close();

  for (int index = 0; index < SIZE; index++) {
    cout << \"#:\" << id[index] << endl;
    cout << \"Beyblade Name: \" << beybladeName[index] << endl;
    cout << \"Product Code: \" << productCode[index] << endl;
    cout << \"Type: \" << type[index] << endl;
    cout << \"Plus Mode: \" << plusMode[index] << endl;
    cout << \"System: \" << system[index] << endl;
    cout << \" \" << endl;
  }
}
  • 你有什么尝试\"使用指针将它们插入主程序中的并行数组\"?
  • 附带说明一下,任何时候你想使用多个并行数组,你可能应该有一个数组,而不是它的元素类型是一个结构/类来保存数组中每个索引的所有信息。
  • @Wind 1)这个话题太大了,2)你怎么在没有教过指针的情况下被分配了一个涉及指针的作业?
  • @john 我被教过指针,但我不知道从哪里开始,那是没有知识的意思,因为指针教我一个值或多个值,当直到数组时,我很模糊......给您带来不便敬请见谅,谢谢回复!!感谢你的帮助!

标签: c++ arrays pointers


【解决方案1】:

主要问题是你有两组数组,一组在main,一组在readCards。您需要main 中的一组数组并将这些数组(使用指针)传递给readCards。像这样

void readCards(int* id, string* beybladeName, string* productCode, string* type, string* plusMode, string* system);

int main()
{
    ifstream inputFile;
    const int SIZE = 10;
    int id[SIZE]; 
    string beybladeName[SIZE];
    string productCode[SIZE];
    string type[SIZE];
    string plusMode [SIZE];
    string system [SIZE];

    readCards(id, beybladeName, productCode, type, plusMode, system);

    return 0;
} 

void readCards(int* id, string* beybladeName, string* productCode, string* type, string* plusMode, string* system)
{
    ...
}

【讨论】:

  • 指针部分怎么样?
  • readCards 有六个指针参数。
  • readCards 可能应该有一个 size 参数,以便它知道何时停止。
  • @jkb 理想情况下,是的,但是看看其余的代码,卡片的数量似乎被硬编码为 10。
  • @Wind 如果不清楚您的readCards 函数不需要更改,除了我在上面所做的更改,并删除您当前在readCards 中的数组声明。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 2021-12-12
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
  • 2017-07-16
相关资源
最近更新 更多