2014-12-29 40 views
0

这应该是30秒钟计入一个txt文件。但它几乎没有使txt本身。我究竟做错了什么?或者是在循环中C++只是无法进行文件处理。 现在只是在文本文件中C++在一个循环内写入一个文件

for (i = 30; i >= 0; i--) 
    { 
     ofstream file; 
     file.open("asd.txt"); 
     file << i; 
     file.close(); 
     Sleep(1000); 
    } 
+0

“但它几乎没有使txt本身”这是什么意思? – 0x499602D2

+4

你是说你只是把文件里面的文字变成'0'?那是因为你不是在追加模式;将openmode'std :: ios_base :: app'添加到'open'。 – 0x499602D2

+0

我想让txt覆盖自己 –

回答

1
什么

移动ofstream的出这样的循环:

// ^^ There is the useless stuff 
ofstream file; 
for (i=0;i<maxs;i++) 
{ 
    system("cls"); 
    secondsLeft=maxs-i; 
    hours=secondsLeft/3600; 
    secondsLeft=secondsLeft-hours*3600; 
    minutes=secondsLeft/60; 
    secondsLeft=secondsLeft-minutes*60; 
    seconds=secondsLeft; 
    cout << hours<< " : " << minutes<< " : " << seconds << " "; 
    file.open ("countdown.txt", ios::trunc); 
    file << hours << " : " << minutes<< " : " << seconds; 
    file.close(); 
    Sleep(1000); 
} 
+0

大声笑,它有很多工作:D –

0

首先,你与每一个循环覆盖输出文件“asd.txt”。您只需为每个会话执行一次文件指针(在循环之外)就可以创建并初始化一个文件指针。关闭文件指针也是一样。

ofstream file; //Create file pointer variable 
file.open("asd.txt"); //Initialize 'file" to open "asd.txt" for writing 
for (i = 30; i >= 0; i--) 
    { 
    file << i; //You'll need to add a new line if you want 1 number per line 
    Sleep(1000); //Assuming this is in microseconds so sleep for 1 second 
    } 
file.close(); //close the file pointer and flushing all pending IO operations to it. 
2

基本上你做什么你创建的对象代表文件,每次你试图打开它。 如果每次使用新引用(对象)访问文件,它都会写入新数据并删除以前的数据。 试着这样做:

int main() 
{ 
    ofstream file; 
    file.open("test.txt"); 
    for (int i = 30; i > 0; --i) 
    { 
     file << i << endl; 
     Sleep(1000); 
    } 
    file.close(); 


    system("pause"); 
    return 0; 
} 
1

你可以声明ofstream退出循环。

如果您必须在循环内使用它,请使用附加模式。

file.open("test.txt", std::ofstream::out | std::ofstream::app);