c++ - 打开文件,删除标点符号,并在C++中附加另一个文件

标签 c++

好吧,直接说一下:我正在处理项目的main.cpp,我想打开一篇文章(prototype.txt),从每一行中删除标点符号,然后将它们附加到另一个.txt文件中(例如。文本)。

我已经写了下面的代码,但是出了点问题:打开example.txt时,文件为空(没有附加行)。知道我的错误在哪里吗?码:

#include <iostream>
#include <cctype>
#include <string>
#include <fstream>
#include "1.h"
#include "2.h"
#include "3.h"

using namespace std;
using std::string;

int main()
{
    std::ifstream file("prototype.txt");
    std::string linestr;
    ofstream myfile;
    myfile.open ("example.txt");


    if(file.is_open() && myfile.is_open())
    {

            while (std::getline(file, linestr))                             //"while" loop for each text 
                                                                            //line
            {
                    for (int i = 0, len = linestr.size(); i < len; i++)     //"for" loop
                    {                                                       //to remove
                        if (ispunct(linestr[i]))                            //punctuation
                        {
                            linestr.erase(i--, 1);
                            len = linestr.size();
                        }
                    }

                    myfile.open ("example.txt",  std::ios_base::app); // append instead of overwrite
                    myfile << linestr << endl;

            }
            myfile.close();

    }

    return 0;
}

最佳答案

您只需要打开文件一次,而不是每一行一次,也可以在完成所有操作后关闭文件:

int main()
{
    std::string linestr = "";

    std::ifstream file("prototype.txt");
    std::ofstream myfile("example.txt", std::ios_base::app);

    if (file.is_open() && myfile.is_open())
    {
        while (std::getline(file, linestr))
        {
            for (std::size_t pos = linestr.find('.'); pos != string::npos; pos = linestr.find('.'))
            {
                linestr.erase(pos, 1);
            }

            myfile << linestr << endl;
        }
    }

    myfile.close();
    file.close();

    return 0;
}

关于c++ - 打开文件,删除标点符号,并在C++中附加另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61988456/

相关文章:

c++ - 是否可以将枚举注入(inject)类范围/命名空间?

c++ - 重载运算符 << : too many parameters for this operator function

c++ - 如何阅读和理解 C & C++ 标准以及其中使用的语言语法?

c++ - 更改娜娜列表框中的值

c++ - 统一缓冲数组元素不正确

c++ - 更改函数指向的内容

c++ - %p 的 printf 格式说明符标志 '0',正确与否?

c++ - 堆 block 修改超过请求的大小

c++ - Python C API 和 C++ 函数

c++ - 将字符串从 UTF-8 转换为 ISO-8859-1