0

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

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;

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

4

3 回答 3

5

Well, ofstream probably overwrites existing contents every time you open it. I mean, every time you open file, write pointer will be placed at the begninning, so even without ios::trunc flag new data written into that file will overwrite existing contents.

To solve the problem, stop reopening ofstream twice for every line of text. File open operation can be slow.

Either that, or try using ios::app flag.

于 2013-09-06T15:23:07.630 回答
2

Move file open and file close operations outside while loop:

#include<iostream>
#include<fstream>

int main()
{
    std::ifstream file( "infile.txt" );
    std::string in1, out1;
    int blockNumber = 0;
    std::ofstream fmatch ("solo_matches.txt",std::ios::out);

    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) );  
        //fmatch.close();  //you don't need this
        //fmatch.open("solo_matches.txt"); //you don't need this
        std::cout << out1 << std::endl;
        fmatch << out1 << std::endl;
    }   
    fmatch.close();
}

And replace

fmatch << out1;

with

fmatch << out1 << endl;

if you need cout and fmatch agreement.

于 2013-09-06T15:38:17.873 回答
1
std::ofstream fmatch("solo_matches.txt", ios::out);
fmatch << ...;
fmatch.close();

打开文件,重写其内容并在关闭流时保存。要将内容附加到文件末尾,可以使用ios::app标志:

std::ofstream fmatch("solo_matches.txt", ios::out | ios::app);

甚至更好,而不是在每次迭代中重新打开文件:

while (...) {
    construct ofstream
    write to file
    close ofstream
}

你可以这样做:

construct ofstream
while (...) {
    write to file
}
close ofstream

还要注意这一行:

out1 = in1.substr( n + 1, ( in1.find_first_of(")", n) - n - 1) ); 

依赖于输入的正确格式,检查返回值会更安全find_first_of

std::size_t pos = in1.find_first_of(")", n);
if (pos != std::string::npos)
{
    out1 = in1.substr( n + 1, pos - n - 1 );
    ...
}
于 2013-09-06T15:28:44.153 回答