I have a simple program which takes user input as a string and output the entered string. The only difference is that I have provided two option to the user,
First to input a basic string.
Second to input a wide string.
The scanf() successfully takes user input for basic string but wscanf() does not prompt for user input and just exit.
Why this is happening with wscanf() and not with scanf() ? How would I take take user input string from wscanf() in the same program.
#include <stddef.h>
#include <stdio.h>
#include <wchar.h>
void basic()
{
char str[100];
printf("Enter string with basic string char: ");
scanf("%s", str);
printf("Entered string : %s \n", str);
}
void wide()
{
wchar_t str[100];
wprintf(L"Enter string with wide string char: ");
wscanf(L"%ls", str);
wprintf(L"Entered string : %ls \n", str);
}
int main(int argc, char **argv)
{
int option = 1;
printf("\n Basic string (char*) vs Wide string (wchar_t*) \n\n");
printf("1. Basic string \n2. Wide string \n");
printf("Enter choice : ");
scanf("%d", &option);
switch(option)
{
case 1:
basic();
break;
case 2 :
wide();
break;
default:
printf("Invalid choice \n");
}
return 0;
}
Output:
1. Basic string :
Basic string (char*) vs Wide string (wchar_t*)
1. Basic string
2. Wide string
Enter choice : 1
Enter string with basic string char: hello
Entered string : hello
2. Wide string :
Basic string (char*) vs Wide string (wchar_t*)
1. Basic string
2. Wide string
Enter choice : 2
The first
scanf()commandscanf("%d", &option);leaves\ninstdin, whichwscanf()is catching. That is what causing the error, i think. I had a similar problem a week ago. You can read more about it here, where you can find good answers and workarounds i have get.You can either put a
getchar()afterscanf()to pull out the\nor avoid the use ofscanf()in total and use an alternative, f.e.sscanf().