开发者

C++ ofstream cannot write to file

Hey I am trying to write some numbers to a file, but when I open the file it is empty. Can you help me out here? Thanks.

/** 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 **/
}


You can't declare an array of integers with a size known only at run-time on the stack. You can declare such an array on the heap however:

int *random_array = new int[random_numbers];

Don't forget to add delete [] random_array; at the end of main() (and delete random_generator; too) to deallocate the memory that you allocated using new. This memory is automatically freed when your program exits, but it's a good idea to release it anyway (if your program ever grows, it's easy to forget to add it in later).

Apart from that, your code looks fine.


There's no need to loop twice or keep an array or vector.

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();


If I just fill in your RandGen class to call rand, the program works fine on 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

Moreover, I see no reason for it not to work on GCC. What version and platform are you running on? Can you provide complete source?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜