简体   繁体   English

如何在C ++中从文件读取乘法字符数组

[英]How to read multiply char arrays from a file in C++

The file "Athlete info.txt" looks like this: 文件“ Athlete info.txt”如下所示:

Peter Gab 2653 Kenya 127

Usain Bolt 6534 Jamaica 128

Bla Bla 2973 Bangladesh -1

Some Name 5182 India 129

What I expect my code to do is read the first string and assign it to the firstName array (for eg Peter is stored in firstName[0] ), read the second string and assign it to lastName array ( for eg Gab is stored in lastName[0] ) and so on..I've tried many different ways and even tried making it all string arrays but it doesn't work. 我希望我的代码执行的操作是读取第一个字符串并将其分配给firstName数组(例如,将Peter存储在firstName[0] ),读取第二个字符串并将其分配给lastName数组(例如,将Gab存储在lastName[0] )等等。我尝试了许多不同的方法,甚至尝试将其全部设置为字符串数组,但是它不起作用。 If anyone can tell me what's wrong in the code or how to go about it, that would be great! 如果有人可以告诉我代码中有什么问题或如何解决,那太好了!

Thanks in advance! 提前致谢!

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();
    }

First of all you are using c++, so let's use std::string, and use classes. 首先,您正在使用c ++,所以让我们使用std :: string并使用类。 Lets create Athlete struct which contains everything your athlete needs: 让我们创建一个运动员结构,其中包含运动员所需的一切:

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;
}

Maybe you could work on this one a bit more and encapsulate it better. 也许您可以多做一些工作并将其封装得更好。

now we will use std::vector to store Athletes and every time we push_back we will call Athelete constructor with read line from input file. 现在我们将使用std :: vector来存储运动员,并且每次我们push_back时,都会使用输入文件中的读取行来调用Athelete构造函数。 Later on you can use range-based for loop to access every single Athlete in vector. 稍后,您可以使用基于范围的for循环来访问vector中的每个运动员。 Also note that ifstream doesn't to be closed manually, it is closed automatically as soon as object reaches out of scope. 还要注意,如果不手动关闭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;
   }
}

The simplest change would be 最简单的更改是

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

This would rely on the input being correctly formatted. 这将取决于输入的格式正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM