0

我正在尝试编写一个程序,从文件中读取名称和票数。但是我无法让 char 数组从文件中正确读取。

void Output(char candidateLastName[][10], long votesRecieved[])
    {
         ifstream Electionr("Election.dat");
         int loop = 0;

         cout << left << setw(10) << "Candidate" << setw(5) << "Votes" << endl;

         Electionr >> candidateLastName[0][10];
         Electionr >> votesRecieved[0];

         cout << setw(10) << candidateLastName[0] << setw(5)
              << votesRecieved[0] << endl;

         for(int loop = 1; loop < 5; loop++)
         {
                 Electionr >> candidateLastName[0][10];
                 Electionr >> votesRecieved[loop];

                 cout << setw(10) << candidateLastName << setw(5)
                      << votesRecieved[loop] << endl;
         }

         Electionr.close();
    }

虽然文件中的数字正确读取,但字符不会。

4

3 回答 3

1
Electionr >> candidateLastName[0][10];

This is reading in a single character. Ignore for a moment that it's reading into the wrong location (the first character of the string at index 1)... I suspect that you want to do something like:

Electionr >> candidateLastName[0];

Also, I presume in your loop you want to use the loop variable instead of 0 to index the array. In that case, why did you not start your loop at zero and avoid duplicating that code?

for(int loop = 0; loop < 5; loop++)
{
    memset( &candidateLastName[loop], 0, 10 );

    Electionr >> candidateLastName[loop];
    Electionr >> votesRecieved[loop];

    cout << setw(10) << candidateLastName[loop] << setw(5)
         << votesRecieved[loop] << endl;
}

(I've also made a minor fix to the cout call above)

Be aware that you may need to explicitly null-terminate your strings (I forced that in my modified loop, but only if you happen to read 9 characters or less - otherwise you will overflow and have problems). I'm not sure if this is handled when reading into character arrays with the >> operator. I never do it for something like this. I use std::string instead.

于 2012-08-13T04:53:28.220 回答
0

首先,您在数组上有一个超出范围的索引。此外,您总是在写入第一个元素。此外,您不应该使用这样的原始数组。如果您要使用固定大小的数组,请至少使用 std::array。但在这种情况下 std::string 是最合适的。

无论如何,很难说出你真正想要什么,但这是我对如何重写代码的最佳猜测。

std::map<std::string, unsigned long> Output()
{
    std::map<std::string, unsigned long> data;
     ifstream Electionr("Election.dat");

     cout << left << setw(10) << "Candidate" << setw(5) << "Votes" << endl;

     while(Electionr.good()){
        std::string name;
        unsigned long votes = 0;

        getline(Electionr, name, ' ');
        Electionr >> votes;

        data[name] = votes;

        cout << setw(10) << name << setw(5)
          << votes << endl;
     }

     return data;
} 
于 2012-08-13T04:43:54.957 回答
0

您的第一次阅读应该是:

         Electionr >> candidateLastName[0];

在你的循环中,你想要:

             Electionr >> candidateLastName[loop];

但是,您假设每个名称的长度最多为 9 个字符(加上一个用于空终止)。

将您的 name 数组和std::string.

void Output(std::string candidateLastName[], long votesRecieved[])
于 2012-08-13T04:45:57.460 回答