wide char

I´m reading the tutorial on C++ available on this site and I´m trying to use a string made of wide characters. So far I´ve tryed this:

1
2
3
4
5
6
7
8
9
10
#include<iostream>

using namespace std;

int main(){
wchar_t prueba = 'ñ';

cout << prueba << endl;

}


An I get:


65521


My questions are:
1) what exactly am I doing? (I think I´m seeing the code for ñ)
2) how can I use a string made of wide character (To output in spanish)?

Thank you!

closed account (18hRX9L8)
You need to find a library that includes these characters somehow. Not sure myself, so some research on Google.
Use wcout instead of cout when outputting wide characters. I thought that changing 'ñ' to L'ñ' would work but for me it just outputs a question mark. Maybe it works better for you.

1
2
3
4
5
6
7
8
#include <iostream>

using namespace std;

int main() {
	wchar_t prueba = L'ñ';
	wcout << prueba << endl;
}
This works for me on Linux:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <locale>
int main()
{
    std::locale::global(std::locale("en_US.utf8"));
    std::wcout.imbue(std::locale());

    wchar_t prueba = L'ñ';
    std::wcout << prueba << '\n';
}

demo: http://liveworkspace.org/code/1UYyyC$0

On Windows, you'd have to do _setmode(_fileno(stdout), _O_U16TEXT); instead of the locale::global/wcout.imbue
Last edited on
Thank you all for your answers,

@usandfriends, according to the tutorial, it´s just a matter of putting L"wide char string ñáüéíó!!!", i´m looking for the easy way, I guess there isn´t...

@Peter87, Code::Block does not compile it.

.cpp|6|error: converting to execution character set: Invalid argument|
||=== Build finished: 1 errors, 0 warnings ===|

But when I change wchar_t prueba = L'ñ'; to wchar_t prueba = 'ñ';, it does compile and outputs nothing visible. Yet if I change 'ñ' to any standard ASCII character, it works...

@Cubbi, I can´t make it run.

.cpp|8|error: converting to execution character set: Invalid argument|
.cpp||In function 'int main()':|
.cpp|6|error: 'stdout' was not declared in this scope|
.cpp|6|error: '_fileno' was not declared in this scope|
.cpp|6|error: '_O_U16TEXT' was not declared in this scope|
.cpp|6|error: 'setmode' was not declared in this scope|
||=== Build finished: 5 errors, 0 warnings ===|

Anyway, I thought it would be much easyer, just like placing L before the string. I couldn´t find any clear explanation on the web either, I´ll do some research tomorrow.

Thanks for your help!
closed account (18hRX9L8)
1
2
3
4
5
6
7
8
#include <stdio.h>

int main(void) {
int c;

for (c = 128; c <= 168; c++) putc(c, stdout);
getchar();
}


Here it is. Sorry it took so long for a simple code.
This should work for Dev C++
Last edited on
This works in Windows with minGW compiler:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <fcntl.h>

int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT);

    wchar_t prueba = L'ñ';
    std::wcout << prueba << '\n';
}
Topic archived. No new replies allowed.