我正在尝试读入文件并从文件中删除所有标点符号。我一直在使用 ispunct() 遍历字符串并检查字符是否是标点符号,但它似乎没有捕捉到所有标点符号。我想知道我是否做错了什么。这是我的代码:
2.txt
你好吗?
我很好,谢谢。
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
//removes punctuation, numbers, and extra spaces
void removeNonAlph(string &tmp)
{
for(int i = 0; i < tmp.length(); i++)
{
if (ispunct(tmp[i]))
tmp.erase(i--, 1);
else if (isdigit(tmp[i]))
tmp.erase(i--, 1);
else if ((tmp[i] == ' ') && (tmp[i+1]) == ' ')
tmp.erase(i--, 1);
}
}
int main(int argc, const char * argv[])
{
ifstream file("2.txt");
string tmp;
string words[500];
while (getline(file, tmp))
{
removeNonAlph(tmp);
toLower(tmp);
cout << tmp << endl;
}
file.close();
}
输出:
你好吗
我很好,谢谢
最佳答案
(评论已移至答案,以便 future 的读者轻松发现)
当心编辑器将非 ASCII 引号放入您的文本文件中。许多编辑器通过使用不同的非 ASCII 字符代码以不同方式显示右引号和左引号来生成看起来更好的“智能引号”。 ispunct
通常只适用于 ASCII 输入。
关于c++ - ispunct() 不检测单引号字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45973529/