Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getline() doesn't read accented characters correctly

I'm trying to get accented characters from user using getline() command, but it does not print them correctly.

I tried to include some libraries as locale, but it was in vain.

Here's my code:

#include <iostream>
#include <cstdlib>
#include <string>
#include <locale>

using namespace std;

class Pers {
public:
    string name;
    int age;
    string weapon;
};

int main()
{
    setlocale(LC_ALL, "");
    Pers pers;

    cout << "Say the name of your character: ";
    getline(cin, pers.name);
    cout << pers.name;
}

When I type: Mark Coração, this is what I get:

Accented characters aren't displaying correctly

How do I fix it?

like image 880
Levy Avatar asked Jan 26 '23 06:01

Levy


1 Answers

Actually, the problem does not come from getline().

std::cout (respectively std::cin) does not support special characters. For this, you have to use std::wcout (respectively std::wcin) which uses wide characters (the size of standard characters limits you to what you can find in the ascii table).
You need to use bigger characters to store the special characters too, that is the case of wide characters.
std::string handles standard characters, std::wstring handles wide characters.

A way to do this could be:

std::wstring a(L"Coração");
std::wcout << a << std::endl;

Output:

Coração


To make it work with getline():

std::wstring a;
getline(std::wcin, a)
std::wcout << a << std::endl;

I hope it can help.

like image 162
Fareanor Avatar answered Feb 05 '23 06:02

Fareanor