我的程序无法读取文件中的所有数据

时间:2019-02-04 22:33:59

标签: c++11

我的程序无法从MarvelIn.txt文件中读取所有数据。 它读取大约29个空格,并且MarvelIn.txt仅包含9个条目,然后出现运行时错误。

我认为我所有的语法都正确,但这是我唯一的错误。不会输出到输出文件“ MarvelOut.txt”。

代码如下:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <stdio.h>
using namespace std;

struct sstruct
{
    string first, last;
    string department;
    int salary;
};

void init2(sstruct s[50])
{
    int maxarray = 50;
    sstruct init = { "Darth", "Vader", "None", 0 };

    for (int i = 0; i < maxarray; i++) {
        s[i] = init;
        cout << "init: " <<s[i].first<<endl;
    }
}

void read(sstruct s[50], int &nums)
{
    int maxarray = 50;
    ifstream inf("MarvelIn.txt");
    int i = 0;
    while (!inf.eof())
    {
        inf >> s[i].first >> s[i].last >> s[i].department >> s[i].salary;
        cout << "read: "<<s[i].first<<s[i].last << s[i].department << 
        s[i].salary << endl;
        i++;
    }
    nums = i;
}

void avg(sstruct s[50], int &nums, double &average2)
{
   int maxarray = 50;
   int i;
   for (i = 0; i < nums; i++)
       average2 += s[i].salary;
   average2 /= nums;
}

void print(sstruct s[50], int nums, double &average2)
{
    int maxarray = 50;
    ofstream outf("MarvelOut.txt");
    int i = 0;
    string temp;
    outf << "the number of professors is: " << nums << endl;
    cout << "the number of professors is: " << nums << endl;
    outf << endl << "The average salary of the professors is: " << average2 << endl;
    outf << "Advisor                    " << "Major     " << " Department     " << "Salary     " << endl;
    for (i = 0; i < nums; i++)
    {
        temp= s[i].last + "," + s[i].first;
        cout << "last, first " << temp << endl;
        outf << left << setw(20) << temp << right << setw(5)<< s[i].department << setw(5) << s[i].salary << setw(8) << endl;
    }
    outf << endl << endl;
}

void swap(sstruct &a, sstruct &b)
{
   sstruct temp;
   temp=a;
   a=b;
   b=temp;
}

void bubbleSort(sstruct s[50], int &nums)
{
    int maxarray = 50;
    int i, j;
    bool swapped;
    for (i = 0; i < nums - 1; i++)
    {
        swapped = false;
        for (j = 0; j < nums - i - 1; j++)
        {
            if (s[j].department > s[j + 1].department)
            {
                swap(s[j], s[j+1]);
                swapped = true;
            }
        }

        // IF no two elements were swapped by inner loop, then break
        if (swapped == false)
            break;
    }
}

int main() {
    int nums=0;
    double average3=0.0;
    const int maxarray = 50;
    sstruct s[maxarray];
    init2(s);
    print(s, nums, average3);
    read(s, nums);
    cout << "numsfirst: " << nums << endl;
    avg(s, nums, average3);
    cout << "nums" << nums << endl;
    bubbleSort(s,nums);
    print(s, nums, average3);
    system("pause");
    return 0;
}

0 个答案:

没有答案