【发布时间】:2013-09-06 15:15:23
【问题描述】:
我正在使用这段代码来提取文本文件每一行的某些部分:
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();
}
但是当我运行代码时,结果并不像我预期的那样。只有最后一个字符串被写入文件。如果我改用这个:
std::cout << out1 << std::endl;
我得到了我需要的确切输出。我不明白有什么区别。
【问题讨论】:
-
那么你用来获得输出的输入是什么?
-
为什么要构造
ofstream,然后close,然后又构造open? -
fmatch.close(); fmatch.open("solo_matches.txt");当然可以完全删除,因为这两行与上一行正好相反。 -
第一个
while的}在哪里? -
看起来你在每次输出后都关闭了流。你应该打开它一次,然后输出你想要的一切,然后关闭它。
标签: c++ file parsing file-io ofstream