我試圖創建一個程序,從文件中讀入數組中的數字,顛倒數組中的數字的順序,然後將這些顛倒的數字輸出到不同的文件。當我已經知道文件中有多少個數字時,我能夠使程序工作,但當我將循環切換到嘗試檢測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。 –
我正在練習使用遞歸函數,所以這是一個遞歸函數,可以顛倒數組 –