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

Cant work with characters like á à ã ă â é è ê

我的代码应该清除任何不是 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 中,它什么都不做,returns 0。我在 Repl.it 上进行了相同的测试,我认为它有点像预期的那样工作。我的 Clion 有问题吗?我做错了什么?

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

#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"; }

This program does not require that 'ф' can be represented in a single char. On OS X and most any modern Linux install this will work just fine, because the source, execution, and console encodings will all be UTF-8 (which supports all Unicode characters).

Things are harder with Windows and there are different possibilities with different tradeoffs.

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

另见

  • Why is "using namespace std;" considered bad practice?

  • How to print Unicode character in C++?