【发布时间】:2016-03-25 18:58:49
【问题描述】:
我正在用法语编程,因此,我需要使用重音字符。我可以通过使用输出它们
#include <locale> 和 setlocale(LC_ALL, ""),但是当我阅读重音字符时似乎有问题。这是我为说明问题而制作的简单示例:
#include <locale>
#include <iostream>
using namespace std;
const string SymbolsAllowed = "+-*/%";
int main()
{
setlocale(LC_ALL, ""); // makes accents printable
// Traduction : Please write a string with accented characters
// 'é' is shown correctly :
cout << "Veuillez écrire du texte accentué : ";
string accentedString;
getline(cin, accentedString);
// Accented char are not shown correctly :
cout << "Accented string written : " << accentedString << endl;
for (unsigned int i = 0; i < accentedString.length(); ++i)
{
char currentChar = accentedString.at(i);
// The program crashes while testing if currentChar is alphanumeric.
// (error image below) :
if (!isalnum(currentChar) && !strchr(SymbolsAllowed.c_str(), currentChar))
{
cout << endl << "Character not allowed : " << currentChar << endl;
system("pause");
return 1;
}
}
cout << endl << "No unauthorized characters were written." << endl;
system("pause");
return 0;
}
这是程序崩溃前的输出示例:
Veuillez écrire du texte accentué : éèàìù
Accented string written : ʾS.?—
我注意到 Visual Studio 的调试器显示我编写的内容与其输出的内容不同:
[0] -126 '‚' char
[1] -118 'Š' char
[2] -123 '…' char
[3] -115 '' char
[4] -105 '—' char
显示的错误似乎表明只能使用 -1 到 255 之间的字符,但是根据ASCII table,我在上面的示例中使用的重音字符的值 不要超过这个限制。
这是弹出的错误对话框图片:Error message: Expression: c >= -1 && c <= 255
有人可以告诉我我做错了什么或给我一个解决方案吗?先感谢您。 :)
【问题讨论】:
-
ASCII 表的范围仅为 0-127。对于 unicode 字符,您需要使用
wchar_t。顺便说一句,在您的系统中char是signed类型,因此调试器将显示不在0-127 范围内的值的负值。备注:char既不是signed char也不是unsigned char -
使用 Unicode。不要使用语言环境。 stackoverflow.com/q/2849010/995714stackoverflow.com/q/2492077/995714
标签: c++ input ascii diacritics strchr