Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
putwchar() function in C/C++
The putwchar() function in C is used to write a wide character to the standard output (stdout). It is the wide character equivalent of the putchar() function and is defined in the <wchar.h> header file.
Syntax
wint_t putwchar(wchar_t wc);
Parameters
- wc − The wide character to be written to stdout
Return Value
- On success: Returns the wide character that was written
- On failure: Returns
WEOFand sets an error indicator
Example 1: Writing Single Wide Character
This example demonstrates writing a single wide character to stdout −
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main() {
setlocale(LC_ALL, "");
wchar_t ch = L'A';
wprintf(L"Character: ");
putwchar(ch);
wprintf(L"\n");
return 0;
}
Character: A
Example 2: Writing Multiple Wide Characters
This example shows how to use putwchar() in a loop to print multiple characters −
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main() {
setlocale(LC_ALL, "");
wprintf(L"Characters: ");
for (wchar_t i = L'a'; i <= L'e'; i++) {
putwchar(i);
putwchar(L' ');
}
wprintf(L"\n");
return 0;
}
Characters: a b c d e
Example 3: Error Checking
This example demonstrates proper error checking with putwchar() −
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main() {
setlocale(LC_ALL, "");
wchar_t ch = L'X';
wint_t result = putwchar(ch);
if (result == WEOF) {
wprintf(L"Error writing character\n");
} else {
wprintf(L"\nSuccessfully wrote character: %lc\n", result);
}
return 0;
}
X Successfully wrote character: X
Key Points
- Always call
setlocale()before using wide character functions - Use
Lprefix for wide character literals - Check return value for error handling
- Use
wprintf()for wide character formatted output
Conclusion
The putwchar() function provides a simple way to output wide characters to stdout. It supports Unicode characters and is essential for internationalization in C programs.
Advertisements
