c - wscanf() 在获取输入时的行为与 scanf() 不同

标签 c string scanf c-strings widestring

我有一个简单的程序,它将用户输入作为字符串并输出输入的字符串。唯一的区别是我为用户提供了两个选项,

首先输入一个基本字符串

其次输入一个宽字符串

scanf() 成功获取基本字符串的用户输入,但 wscanf() 不会提示用户输入并直接退出。

为什么 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;
} 

输出:

<强>1。基本字符串:

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

方向。

Code 对 stdin 的第一次使用是 scanf("%d", &option) 建立一个面向字节的流

在使用 wscanf(L"%ls", str); 之后是 UB。坚持一种方向或重新打开文件。

Each stream has an orientation. After a stream is associated with an external file, but before any operations are performed on it, the stream is without orientation. Once a wide character input/output function has been applied to a stream without orientation, the stream becomes a wide-oriented stream. Similarly, once a byte input/output function has been applied to a stream without orientation, the stream becomes a byte-oriented stream. Only a call to the freopen function or the fwide function can otherwise alter the orientation of a stream. (A successful call to freopen removes any orientation.) C11 §7.21.2 4.

类似的问题适用于 stdout

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

相关文章:

c - LCD 反文(CV12864C & RA6963 Controller )

java - 字符串什么时候缓存它的哈希码?是在 String 对象创建期间还是在调用 hashcode 方法后?

c++ - 如何使用 stringstream 在字符串中保留引号?

c - sscanf : get first and last token in a string

c - 重新分配(): invalid next size error in C program

比较 char 数组的两个值

c++ - 根据索引和优先级对列表数量进行排序

ios - CollectionView [__NSCFConstantString _isResizable] : unrecognized selector sent to instance

c - 如何在 C 中使用 EOF 标准输入

c - scanf 不起作用(整数)