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:
How do I fix it?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With