如何标记现有文件的行?

时间:2017-01-20 13:22:42

标签: c++ file io

假设我有一个包含以下内容的文本文件:

  

     

得分

     

     

7

     

     

     

...

我希望能够标记这些行,以便在程序运行后,文件看起来像:

  

1.Four

     

2.score

     

3.and

     

4.seven

     

5.years

     

6.ago

     

...

我已经准备好了解决方案;但是,我发现它很重,而且有一个问题就是在最后一行标记一个......

std::string file = "set_test - Copy.txt";
        std::ifstream in_test{file};
        std::vector<std::string> lines;
        while(in_test) {
            std::string temp;
            getline(in_test, temp);

            lines.push_back(temp);
        }
        in_test.close();

        std::ofstream out_test{file};
        for(unsigned int i = 0; i < lines.size(); ++i) {
            out_test << i+1 << '.' << lines[i] << '\n';
        }

除了重量级之外,此解决方案还标记了最后一行文字之外的行。

有没有人能更好地解决这个问题?

1 个答案:

答案 0 :(得分:0)

问题的原因是这个结构

while (stream is good)
    read from stream
    do something

因为它会读得太多。 (有关解释,请参阅this Q&A。)
发生的事情是最后一个getline,即实际到达文件末尾的temp将失败,并使while (attempt to read) do something with the result 为空。 然后将该空行添加到您的行中。

&#34;规范&#34;流读取循环结构是

std::string temp;
while (getline(in_test, temp)) {
    lines.push_back(temp);
}

在你的情况下,

std::ifstream in_test{"set_test - Copy.txt";}
std::ofstream out_test{"set_test - Numbered.txt"};
if (!in_test || !out_test) {
    std::cerr << "There was an error in the opening of the files.\n";
    return;
}

int i = 1;
std::string line;
while (getline(in_test, line) && out_test << i << '.' << line << '\n') {
    i++;
}

如果你写一个不同的文件,除了最后一行之外你不需要存储任何东西;你可以马上写下每一行 如果要更换原件,可以在之后用旧的替换旧的 像这样:

border-image: linear-gradient(orange 33%, blue 33%, blue 66%, red 66%) 1 100%;