8

在你开始之前;是的,我知道这是一个重复的问题,是的,我已经查看了发布的解决方案。我的问题是我无法让他们工作。

bool invalidChar (char c)
{ 
    return !isprint((unsigned)c); 
}
void stripUnicode(string & str)
{
    str.erase(remove_if(str.begin(),str.end(), invalidChar), str.end()); 
}

我在“Prusæus, Ægyptians”上测试了这种方法,但它没有做任何我也试图替代isprint的方法isalnum

当我在程序的另一部分转换 string->wstring->string 时,就会出现真正的问题。如果 string->wstring 转换中有 unicode 字符,则转换会停止。

参考:

如何从字符串中去除非 ASCII 字符?(在 C# 中)

如何从 C++ 中的字符串中去除所有非字母数字字符?

编辑:

我仍然想删除所有非 ASCII 字符,不管它是否有帮助,这就是我崩溃的地方:

// Convert to wstring
wchar_t* UnicodeTextBuffer = new wchar_t[ANSIWord.length()+1];
wmemset(UnicodeTextBuffer, 0, ANSIWord.length()+1);
mbstowcs(UnicodeTextBuffer, ANSIWord.c_str(), ANSIWord.length());
wWord = UnicodeTextBuffer; //CRASH

错误对话框

MSVC++ 调试库

调试断言失败!

程序://我的项目

文件:f:\dd\vctools\crt_bld\self_x86\crt\src\isctype.c

行://以上

表达式:(无符号)(c+1)<=256

编辑:

更复杂的是:我从中读取的 .txt 文件是 ANSI 编码的。里面的一切都应该是有效的。

解决方案:

bool invalidChar (char c) 
{  
    return !(c>=0 && c <128);   
} 
void stripUnicode(string & str) 
{ 
    str.erase(remove_if(str.begin(),str.end(), invalidChar), str.end());  
}

如果其他人想复制/粘贴这个,我可以勾选这个问题。

编辑:

供将来参考:尝试使用__isascii、iswascii命令

4

3 回答 3

12

解决方案:

bool invalidChar (char c) 
{  
    return !(c>=0 && c <128);   
} 
void stripUnicode(string & str) 
{ 
    str.erase(remove_if(str.begin(),str.end(), invalidChar), str.end());  
}

编辑:

供将来参考:尝试使用 __isascii、iswascii 命令

于 2013-04-04T14:04:55.883 回答
2

至少有一个问题存在于您的invalidChar职能中。它应该是:

return !isprint( static_cast<unsigned char>( c ) );

如果a为负数(isprint是未定义的行为charunsignedcharUNIT_MAX+1 + c). Passing such a value to

于 2012-04-16T17:28:38.860 回答
0

isprint取决于语言环境,因此相关字符必须在当前语言环境中可打印。

如果您想要严格的 ASCII,请检查 [0..127] 的范围。如果您想要可打印的 ASCII,请检查范围和isprint.

于 2012-04-16T18:31:55.837 回答