【发布时间】:2010-04-06 02:21:46
【问题描述】:
嘿,我正在尝试将一些数字写入文件,但是当我打开文件时它是空的。你能帮帮我吗?谢谢。
/** 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 **/
}
【问题讨论】:
-
一看就知道这段代码不会编译——“random_array”数组是用一个非常量变量声明的。你应该发布你的实际代码,我怀疑你已经过度简化了
-
@Terry:这是一个非标准扩展。
-
@Potatocorn:真的吗?天哪,在哪个平台上?
-
无论如何,
random_generator是动态分配的吗?例如,为什么总是首选自动分配,您正在泄漏它。另外,等到需要变量后再声明它们;否则您的代码很难阅读。此外,您将文件变量命名为File,它不适合您的其他变量,这很奇怪。它可能只是ofstream file(file_name.c_str());。此外,无需手动关闭文件,它会自动完成。最后,您的错误在这里:int random_array [random_numbers];。需要是std::vector。 -
我发现即使在程序退出前立即显式关闭文件并释放内存总是一个好主意,因为否则,如果该代码被移动,很容易忘记清理。
标签: c++ file ifstream ofstream file-writing