[英]How to make a member function of a class in C++ generate a different random number each time it is called?
[英]How to make c++ function write on the last line of the output file each time it is called
現在的問題是如何使輸出中的文件有1
對1號線, 2
2號等,因為它是程序重寫每次執行循環的文件,你所剩下的只是9
輸出文件。
#include <fstream>
using namespace std;
void function (int i)
{
ofstream output("result.out");
output << i << endl;
output.close();
}
int main()
{
for (int i=1; i<10; i++)
{
function(i);
}
return 0;
}
將std::ios::app
傳遞給std::ofstream
構造函數的第二個參數。 即
std::ofstream output("result.out", std::ios::app);
如果您真的想按照自己的方式做:
void function (int i)
{
ofstream output("result.out", std::ios::app);
output << i << endl;
output.close();
}
int main()
{
for (int i=1; i<10; i++)
{
function(i);
}
return 0;
}
添加ios :: app不會刪除文件的內容,但會在其中添加文本。 它有一個缺點-如果您想再次調用循環,則舊數據仍然存在。
但是我建議將for()循環移入函數中。
void function (int i)
{
ofstream output("result.out");
for(int j = 1, j < i; j++
output << j << endl;
output.close();
}
int main()
{
function(10);
return 0;
}
結果是相同的,您避免重復打開和關閉文件,但仍可以將其用作功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.