我有一个简单的程序,它将用户输入作为字符串并输出输入的字符串。唯一的区别是我为用户提供了两个选项,
首先输入一个基本字符串。
第二个输入宽字符串。
成功地接受了用户对基本字符串的输入,但没有提示用户输入,然后退出。
为什么这发生在wscanf()而不是scanf()上?如何从同一程序中的wscanf()获取用户输入字符串。

#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;
}

输出:
一。基本字符串:
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。宽字符串:
Basic string (char*) vs Wide string (wchar_t*)

1. Basic string

2. Wide string

Enter choice : 2

最佳答案

wscanf() behaving differently than scanf() when taking input
方向。
代码的第一个用途是建立一个面向字节的流。
以下使用stdin是UB。坚持一个方向或重新打开文件。
每个流都有一个方向。流与外部文件关联后,但是
在对其执行任何操作之前,流没有方向。一次宽
字符输入/输出功能已应用于无方向的流,则
流变为宽方向流。同样,一旦字节输入/输出函数
如果应用于没有方向的流,则该流将成为面向字节的流。
只有对freopen函数或fwide函数的调用才能改变
溪流的方向。(成功调用freopen会删除任何方向。)
C11第7.21.2节4。
类似的问题也适用于scanf("%d", &option)

关于c - wscanf()的行为与scanf()的行为不同,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58474894/

10-10 23:16