嘿,我正在尝试将一些数字写入文件,但是当我打开文件时它是空的。你能帮我一下吗?谢谢。
/** 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/