返回垃圾号码,我不知道为什么

时间:2016-07-05 20:41:15

标签: c++

我试图创建一个程序,将文件中的数字读入数组,反转数组中数字的顺序,然后将这些反转的数字输出到不同的文件中。当我已经知道文件中有多少个数字时,我能够让程序工作,但是当我将循环切换到试图检测EOF(文件结束)时,我遇到了困难。当我运行此代码时,它将打印文件中的两个数字,其余的是垃圾值。任何帮助?

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

const int NUMS = 5;

void reverseArray(int number[], int first, int last)
{
   int temp;

   if (first >= last)
   {
      return;
   }

   temp = number[first];
   number[first] = number[last];
   number[last] = temp;

   reverseArray(number, first + 1, last - 1);
}

int main()
{
   //Create file objects
   ifstream inputFile;
   ofstream outputFile;
   string inputName;
   string outputName;

   //Prompt user for file names
   cout << "What is the name of the input file?" << endl;
   getline(cin, inputName);

   cout << "What would you like the output file to be called?" << endl;
   getline(cin, outputName);

   //open user named files
   inputFile.open(inputName);
   outputFile.open(outputName);

   int numsFromFile;

   int numbers[NUMS];

   int fileCount = 0;

   /*
   //read in numbers from a file ********THIS WORKS BUT WHEN I CHANGE IT BELOW IT DOES NOT******
   for (int count = 0; count < NUMS; count++)
   {
   inputFile >> number[count];
   }
    */

   //Try to read numbers in detecting the EOF
   while (inputFile >> numsFromFile)
   {
      inputFile >> numbers[fileCount];
      fileCount++;
   }

   //print numbers to screen
   for (int count = 0; count < fileCount; count++)
   {
      cout << numbers[count] << endl;
   }

   //reverse array
   reverseArray(numbers, 0, 4);

   cout << "Reversed is: " << endl;

   //print reversed array
   for (int count = 0; count < NUMS; count++)
   {
      cout << numbers[count] << endl;
   }

   //output numbers to a file
   for (int count = 0; count < NUMS; count++)
   {
      outputFile << numbers[count] << endl;
   }

   outputFile.close();
   inputFile.close();

   return 0;
}

1 个答案:

答案 0 :(得分:2)

行中有一个错误:

while (inputFile >> numsFromFile)
{
   inputFile >> numbers[fileCount];
   fileCount++;
}

您最终阅读并丢弃第一个号码,第三个号码,第五个号码等。将其更改为:

while (inputFile >> numsFromFile)
{
   numbers[fileCount] = numsFromFile;
   fileCount++;
}