【问题标题】:How to read multiply char arrays from a file in C++如何从 C++ 文件中读取乘法字符数组
【发布时间】:2016-12-10 16:15:43
【问题描述】:

“运动员信息.txt”文件如下所示:

Peter Gab 2653 Kenya 127

Usain Bolt 6534 Jamaica 128

Bla Bla 2973 Bangladesh -1

Some Name 5182 India 129

我希望我的代码做的是读取第一个字符串并将其分配给firstName 数组(例如,彼得存储在firstName[0]),读取第二个字符串并将其分配给lastName 数组(对于例如,Gab 存储在lastName[0]) 等等..我尝试了许多不同的方法,甚至尝试将其全部设为字符串数组,但它不起作用。如果有人能告诉我代码有什么问题或如何解决,那就太好了!

提前致谢!

void readInputFromFile()
    {
        ifstream inputData;
        inputData.open("Athlete info.txt");

        const int SIZE=50;
        char firstName[SIZE],
             lastName[SIZE],
             athleteNumber[SIZE],
             country[SIZE];
        int  athleteTime[SIZE];

        int numOfCharacters=0;

        if (inputData.is_open())
        {
            int i=0;

            while(!inputData.eof())
            {
                inputData >> firstName[i]; 
                inputData >> lastName[i]; 
                inputData >> athleteNumber[i];
                inputData >> country[i]; 
                inputData >> athleteTime[i];
                i++;
                numOfCharacters++;
            }

            for (int i=0; i < numOfCharacters; i++ )
            {
                cout << "First Name: " << firstName[i];
                cout << "Last name: " << lastName[i];
                cout << "AthleteNumber: " << athleteNumber[i];
                cout << "Country: " << country[i];
                cout << "Time taken: " << athleteTime[i];
                cout << endl;
            }

        }
        else
        {
            cout << "ERROR" << endl;
        }
        inputData.close();
    }

【问题讨论】:

  • while(!inputData.eof()) stackoverflow.com/questions/5605125/…
  • 您正在阅读 1 个字符。而不是一个字符串。如果你被允许使用c++,这段代码会更简洁更好。我的意思是 std::string 而不是字符串的 c 数组..

标签: c++ arrays string function file


【解决方案1】:

首先你使用的是c++,所以让我们使用std::string,并使用类。让我们创建 Athlete 结构体,其中包含您的运动员所需的一切:

struct Athlete {
    Athlete() = default;
    Athlete(std::stringstream &stream) {
        stream >> firstName 
               >> lastName 
               >> athleteNumber 
               >> country 
               >> athleteTime;
    }
    // every Athlete is unique, copying should be prohibited
    Athlete(const Athlete&) = delete;

    std::string firstName;
    std::string lastName;
    std::string athleteNumber;
    std::string country;
    std::string athleteTime;
}

也许你可以在这方面多做一些工作,把它封装得更好。

现在我们将使用 std::vector 来存储 Athlete 并且每次我们 push_back 我们都将调用 Athelete 构造函数并从输入文件中读取行。稍后您可以使用基于范围的 for 循环来访问向量中的每个 Athlete。另请注意,ifstream 不会手动关闭,它会在对象超出范围时自动关闭。

void readInputFromFile() {
   ifstream inputData("Athlete info.txt");
   std::vector<Athlete> athletes;

   std::string line;
   std::stringstream ss;

   if (inputData.is_open() {
      while (getline(inputData, line)) {
         ss.str(line);
         // directly construct in-place
         athletes.emplace_back(ss);
      }

      for (const Athlete& a : athletes) {
         /* ...*/
      }
   } else {
      std:cerr << "ERROR" << std::endl;
   }
}

【讨论】:

  • 很好的答案。我不知道您可以将std::stringstream 传递给getline。我将在我自己的代码中使用它!
  • 非常感谢!它包含很多我尚未完成的内容,所以我发现它有点混乱,但仍然感谢!
  • 别着急问什么,我很乐意帮助你了解自己
  • 您已禁止复制并在Athlete 对象上执行push_back。这对我来说似乎有点争议。我认为你应该使用emplace_back。 (是的,我知道编译器无论如何都会调用移动构造函数,这似乎更合乎逻辑)。
【解决方案2】:

最简单的改变是

while(inputData >> firstName[i])
{
    inputData >> lastName[i]; 
    inputData >> athleteNumber[i];
    inputData >> country[i]; 
    inputData >> athleteTime[i];
    i++;
    numOfCharacters++;
}

这取决于输入的格式是否正确。

【讨论】:

  • 谢谢,但这不会将名字 Peter 保存在 firstName[0] 中。这是因为当我后来 cout
  • 嗯,这很奇怪!我确定我测试过它并且它有效......但是@Marzi 的答案是更好的答案,如果你能够脱离旧教科书的风格。
猜你喜欢
  • 1970-01-01
  • 2012-05-30
  • 2014-06-06
  • 1970-01-01
  • 2019-05-07
  • 2019-11-27
  • 1970-01-01
  • 2017-03-18
  • 1970-01-01
相关资源
最近更新 更多