#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;
void make_array(ifstream &num, int (&array)[50]);
int main(){
ifstream file; // variable controlling the file
char filename[100]; /// to handle calling the file name;
int array[50];
cout << "Please enter the name of the file you wish to process:";
cin >> filename;
cout << "\n";
file.open(filename);
if(file.fail()){
cout << "The file failed to open.\n";
exit(1);
}
else{
cout << "File Opened Successfully.\n";
}
make_array(file, array);
file.close();
return(0);
}
void make_array(ifstream &num, int (&array)[50]){
int i = 0; // counter variable
while(!num.eof() && i < 50){
num >> array[i];
i = i + 1;
}
for(i; i>=0; i--){
cout << array[i] << "\n";
}
}
좋아요,이 코드는 지금까지 제 코드입니다. 배열의 내용을 출력 할 때 예상되는 출력 전에 실제로 두 개의 큰 음수를 얻습니다. 예를 들어 파일에 1 2 3 4가 있으면 내 프로그램에서 -6438230 -293948 1 2 3 4를 출력하고 있습니다.배열의 출력이 잘못되었습니다.
누군가 내가 왜이 우스운 값을 얻고 있는지 말해 줄 수 있습니까?
사람들이 100 자 이상의 파일 이름을 입력하지 못하도록하는 것은 무엇입니까? 'std :: string'을 사용하면 버퍼 오버 플로우를 유발하기 쉽습니다. 또한 배열 입력이 사용되기 전에 성공했는지 확인하지 않습니다. 또한 단계별로 프로그램을 디버깅해야합니다.이 시점에서 그 값의 출처를 확인해야합니다. 조건으로'eof'를 사용하면 [버그를 일으킬 수 있습니다] (http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) 또한 올바르게 수정합니다. 성공 문제에 대한 점검 입력을 수정합니다. – chris