我试图创建一个程序,从文件中读入数组中的数字,颠倒数组中的数字的顺序,然后将这些颠倒的数字输出到不同的文件。当我已经知道文件中有多少个数字时,我能够使程序工作,但当我将循环切换到尝试检测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,2,3,4读入数组,那么你从结尾开始,输出4,3,2,1。 –
我正在练习使用递归函数,所以这是一个递归函数,可以颠倒数组 –