C++ ofstream 无法写入文件

标签 c++ file ifstream ofstream file-writing

嘿,我正在尝试将一些数字写入文件,但是当我打开文件时它是空的。你能帮我一下吗?谢谢。

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

最佳答案

您不能在堆栈上声明大小仅在运行时已知的整数数组。但是,您可以在堆上声明这样的数组:

int *random_array = new int[random_numbers];

不要忘记在 main() 末尾添加 delete [] random_array; (以及 delete random_generator;)来释放使用分配的内存。当您的程序退出时,该内存会自动释放,但无论如何释放它都是一个好主意(如果您的程序不断增长,很容易忘记稍后添加它)。

除此之外,您的代码看起来不错。

关于C++ ofstream 无法写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2582312/

相关文章:

ruby-on-rails - 在 Rails 的数据库中将用户输入保存为 xml 文件

c++ - 为什么 ifstream 两次返回输入文件的最后一个值?

c++ - 在 C++ 中解析 .dat 文件

c++ - WT 保存文件对话框窗口?

c++ - 有没有一种方法可以防止单词在C++输出中获得 'cut'?

c++ - CImg库可以画粗线吗

c++ - swig 接口(interface)文件的正确 sstream 包含路径是什么?

c++ - 使用两个不同版本的boost

c++ - Qt编辑无框窗口

jQuery文件上传如何获取排队和上传的文件数量