2

ちょっと私はファイルにいくつかの数字を書き込もうとしていますが、ファイルを開くとそれは空です。ここで私を助けてくれませんか?ありがとう。

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

3 に答える 3

4

スタック上で実行時にのみ既知のサイズを持つ整数の配列を宣言することはできません。ただし、ヒープでそのような配列を宣言できます。

int *random_array = new int[random_numbers];

を使用して割り当てたメモリの割り当てを解除するためにdelete [] random_array;、 main() の最後に追加することを忘れないでください。このメモリは、プログラムが終了すると自動的に解放されますが、とにかく解放することをお勧めします (プログラムが大きくなると、後で追加するのを忘れがちです)。delete random_generator;new

それとは別に、コードは問題なく見えます。

于 2010-04-06T02:26:52.003 に答える
0

RandGenクラスに入力して呼び出すだけの場合rand、プログラムはMac OSX10.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で動作しない理由はわかりません。どのバージョンとプラットフォームで実行していますか?完全なソースを提供できますか?

于 2010-04-06T02:37:41.570 に答える
0

2回ループしたり、配列やベクトルを保持したりする必要はありません。

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();
于 2010-04-06T02:45:39.900 に答える