小编goc*_*n76的帖子

在循环中写入文件(std :: ofstream)只写入最后一行

我正在使用此代码提取文本文件的每一行的某些部分:

std::ifstream file( "infile.txt" );
std::string in1, out1;
int blockNumber = 0;

while( getline( file, in1 ) ) 
{   
    int n = 0;
    int i = 0;

    while( i <= blockNumber )
    {   
        n = in1.find_first_of("(", n + 1); 
        i++;
    }   
    out1 = in1.substr( n + 1, ( in1.find_first_of(")", n) - n - 1) );  
    ofstream fmatch ("solo_matches.txt",ios::out);
    fmatch.close();
    fmatch.open("solo_matches.txt");
    fmatch << out1;
    fmatch.close();
} 
Run Code Online (Sandbox Code Playgroud)

但是当我运行代码时,结果并不像我预期的那样.只有最后一个字符串被写入该文件.如果我改用它:

 std::cout << out1 << std::endl;
Run Code Online (Sandbox Code Playgroud)

我得到了我需要的确切输出.我不明白有什么区别.

c++ file-io parsing file ofstream

0
推荐指数
1
解决办法
1万
查看次数

标签 统计

c++ ×1

file ×1

file-io ×1

ofstream ×1

parsing ×1