goc*_*n76 0 c++ file-io parsing file 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)
我得到了我需要的确切输出.我不明白有什么区别.
好吧,每次打开时,ofstream可能会覆盖现有内容.我的意思是,每次打开文件时,写指针都会被放置在begninning中,因此即使没有ios::trunc标记,新数据写入该文件也会覆盖现有内容.
要解决此问题,请为每行文本停止重新打开两次流.文件打开操作可能很慢.
要么是,要么尝试使用ios::app旗帜.
| 归档时间: |
|
| 查看次数: |
13910 次 |
| 最近记录: |