C++ 返回垃圾编号,我不知道';我不知道为什么

C++ 返回垃圾编号,我不知道';我不知道为什么,c++,C++,我试图创建一个程序,从一个文件中读入一个数组中的数字,反转数组中数字的顺序,然后将这些反转的数字输出到另一个文件中。当我已经知道文件中有多少个数字时,我能够让程序工作,但是当我切换循环尝试检测EOF(文件结束)时,我遇到了困难。当我运行此代码时,它将打印文件中的两个数字,其余是垃圾值。有什么帮助吗 #include "stdafx.h" #include <iostream> #include <fstream> #include <string> usin

我试图创建一个程序,从一个文件中读入一个数组中的数字,反转数组中数字的顺序,然后将这些反转的数字输出到另一个文件中。当我已经知道文件中有多少个数字时,我能够让程序工作,但是当我切换循环尝试检测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;
}
#包括“stdafx.h”
#包括
#包括
#包括
使用名称空间std;
常数int NUMS=5;
void reversearlay(整数[],整数第一,整数最后)
{
内部温度;
如果(第一个>=最后一个)
{
回来
}
温度=编号[第一];
编号[第一]=编号[最后];
编号[最后]=温度;
reverseArray(数字,第一个+1,最后一个-1);
}
int main()
{
//创建文件对象
ifstream输入文件;
流输出文件;
字符串输入名;
字符串输出名;
//提示用户输入文件名
cout numsFromFile)
{
输入文件>>数字[文件计数];
fileCount++;
}
//在屏幕上打印数字
for(int count=0;countcout行中有一个错误:

while (inputFile >> numsFromFile)
{
   inputFile >> numbers[fileCount];
   fileCount++;
}
您最终读取并丢弃第一个号码、第三个号码、第五个号码等。将其更改为:

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

你真的要反转数组吗?为什么不能按相反的顺序输出呢?如果你把1,2,3,4读入数组,然后从末尾开始,输出4,3,2,1。我正在练习使用递归函数,所以这是一个反转数组的递归函数!谢谢!我在你发布之前就找到了它,但是谢谢你的q回信!