不能使用像 á à ã ă â é è ê 这样的字符

问题描述

我的代码应该清除任何不是 a-zA-Z 的字符。对于其他字符,例如 á à ã ă â é è ê 如果我可以使它工作,我会将它们从 á 更改为 a,将 è 更改为 e 等。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int counter=0;
    string* word = new string[1];
    string b ="áhelloá";//nothing

    word[0] = "áapple_.Dogá.";//doesnt work
    //word[0] = "apple_.Dog.";//if there is no characters like á it works
    cout<<endl<<word[0].length()<<endl;

    for (int i = 0; i < word[0].length(); ++i)
    {
        if(word[0][i] >= 'A' && word[0][i] <='Z' || word[0][i] >= 'a' && word[0][i] <='z')
        {
            cout<<"Current: "<<word[0][i]<<endl;//shows what characters passed if
        }
        else
        {
            cout<<"Erased: "<<word[0][i]<<endl;//shows what was erased
            word[0].erase(i,1);//deletes char
            i--;
        }
    }

    cout<<endl<<word[0];//prints final word,after erase

    return 0;
}

如果我在 á 中使用例如 Clion 运行我的代码,它不会执行任何操作并返回 0。我在 Repl.it 上测试了同样的东西,我认为它有点按预期工作。我的Clion有问题吗?我做错了什么?

解决方法

您可以在 Windows 中使用 wcoutwstring 处理 C++ 中的 Unicode 字符:

#include <iostream>
#include <string>
#include <io.h>
#include <fcntl.h>
using namespace std;

int main()
{
    _setmode(_fileno(stdout),_O_U16TEXT); //set the mode of the output file handle to take only UTF-16 data
    int counter=0;
    wstring word;

    word = L"áapple_.Dogá.";
    cout<<'\n'<<word.length()<<'\n';

    for (int i = 0; i < word.length(); ++i)
    {
        if(word[i] >= 'A' && word[i] <='Z' || word[i] >= 'a' && word[i] <='z')
        {
            wcout<<"Current: "<<word[i]<<'\n';
        }
        else
        {
            wcout<<"Erased: "<<word[i]<<'\n';
            word.erase(i,1);
            i--;
        }
    }

    wcout<<'\n'<<word;
    return 0;
}

结果:

Erased: á
Current: a
Current: p
Current: p
Current: l
Current: e
Erased: _
Erased: .
Current: D
Current: o
Current: g
Erased: á
Erased: .

appleDog

对于“为什么它适用于 repl.it?”这个问题:

应该注意的是,不同的编译器和平台对 Unicode 字符的处理非常不同。引用 @bames53 :

#include <iostream>

int main() {
    std::cout << "Hello,ф or \u0444!\n"; }

这个程序不要求 'ф' 可以用单个表示 字符。在 OS X 和大多数现代 Linux 安装上,这将正常工作 很好,因为源代码、执行代码和控制台编码都将是 UTF-8(支持所有 Unicode 字符)。

Windows 更难,而且有不同的可能性 有不同的权衡。

顺便说一句,IMO 您无缘无故地使用动态数组。一个 wstring 就足够了。

另见

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...