2010-04-06 10 views
2

안녕하세요 저는 파일에 숫자를 쓰려고하는데, 파일을 열면 비어 있습니다. 여기서 나를 도울 수 있니? 감사.C++ forstream은 파일에 쓸 수 없습니다.

/** main function **/ 
int main(){ 

    /** variables **/ 
    RandGen* random_generator = new RandGen; 
    int random_numbers; 
    string file_name; 

    /** ask user for quantity of random number to produce **/ 
    cout << "How many random number would you like to create?" << endl; 
    cin >> random_numbers; 

    /** ask user for the name of the file to store the numbers **/ 
    cout << "Enter name of file to store random number" << endl; 
    cin >> file_name; 

    /** now create array to store the number **/ 
    int random_array [random_numbers]; 

    /** file the array with random integers **/ 
    for(int i=0; i<random_numbers; i++){ 
     random_array[i] = random_generator -> randInt(-20, 20); 
     cout << random_array[i] << endl; 
    } 

    /** open file and write contents of random array **/ 
    const char* file = file_name.c_str(); 
    ofstream File(file); 

    /** write contents to the file **/ 
    for(int i=0; i<random_numbers; i++){ 
     File << random_array[i] << endl; 
    } 

    /** close the file **/ 
    File.close(); 

    return 0; 
    /** END OF PROGRAM **/ 
} 
+1

이 코드는 컴파일되지 않습니다. "random_array"배열은 길이가 아닌 변수로 선언됩니다. 실제 코드를 게시해야합니다. 단순화 된 것으로 의심됩니다. –

+0

@ 테리 : 비표준 확장입니다. – Potatoswatter

+0

@Potatocorn : 정말요? 좋은 천국, 어떤 플랫폼? – Cameron

답변

4

실행시에만 알려진 크기의 정수 배열을 스택에 선언 할 수 없습니다. 당신은 그러나 힙에 같은 배열을 선언 할 수

int *random_array = new int[random_numbers]; 

new을 사용하여 할당 할당을 취소 할) (주 (너무 delete random_generator;) 메모리의 끝에 delete [] random_array;를 추가하는 것을 잊지 마십시오. 이 메모리는 프로그램이 종료 될 때 자동으로 해제되지만 어쨌든 해제하는 것이 좋습니다 (프로그램이 커지면 나중에 추가하는 것을 잊어 버리기 쉽습니다).

그 외에도 코드가 정상적으로 보입니다.

+0

고마워 ... 네 말이 맞아. – user69514

+0

대신 std :: vector를 제안할까요? :) –

+1

-1, 죄송합니다. 'std :: vector'를 사용하면 직접 할 이유가 없습니다. – GManNickG

0

rand을 호출하기 위해 RandGen 클래스를 채우는 경우, 프로그램은 Mac OS X 10.6에서 정상적으로 작동합니다.

How many random number would you like to create? 
10 
Enter name of file to store random number 
nums 
55 
25 
44 
56 
56 
53 
20 
29 
54 
57 
Shadow:code dkrauss$ cat nums 
55 
25 
44 
56 
56 
53 
20 
29 
54 
57 

또한 GCC에서 작동하지 않을 이유가 없습니다. 어떤 버전과 플랫폼을 실행하고 있습니까? 완전한 소스를 제공 할 수 있습니까?

+0

'int random_array [random_numbers];'일정하지 않은 크기의 비 동적 배열? – GManNickG

+0

@GMan : * on GCC *. – Potatoswatter

+0

어, 공정하지만 OP가 비표준 C++를 프로그램하고 싶다는 표시가 보이지 않습니다. – GManNickG

0

두 번 반복하거나 배열이나 벡터를 유지할 필요가 없습니다.

const char* file = file_name.c_str(); 
ofstream File(file); 

for(int i=0; i<random_numbers; i++){ 
    int this_random_int = random_generator -> randInt(-20, 20); 
    cout << this_random_int << endl; 
    File << this_random_int << endl; 
} 

File.close(); 
+0

가끔은 버그를 지키고 스쿼시하지 않고 공부하는 것이 유용합니다. – Potatoswatter

관련 문제