gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:08:59 27 4
gpt4 key购买 nike

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

首先输入一个基本字符串

其次输入一个宽字符串

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com