好吧,直接说一下:我正在处理项目的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/