如何使用“scanf"输入特定的字母? [英] How to use "scanf" to input specific letter?

查看:76
本文介绍了如何使用“scanf"输入特定的字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我在高中时的知识.

from my knowledge in high school.

scanf("%[^A-Z]s", input);

意思是输入可以是任何字符,但大写字母除外.

it is mean input can be any characters but except capital letter.

但是如果我只想接收输入字符 [A-F] 我该怎么做?

but in case of i want to receive input only character [A-F] how can i do it?

在我看来应该这样写:

scanf("%[A-Z]s", input);

看起来您使用了正则表达式,但无论如何它不起作用

It looks like you use regex but anyway it was't work

所以,当我运行它

$./a.out 
asdfasdfABC 
`[]@

[] 是一些外星字符,但我打不出来.

[] is some alien character but i can not type.

推荐答案

问题很可能是您没有检查错误,即使 scanf 调用失败也打印字符串.

The problem is, most likely, that you do not check for errors, and print the string even when the scanf call fails.

使用模式 "%[AZ]" 你只扫描大写字母,如果你输入的字符串不是以大写字母开头 scan 将失败.这当然意味着字符串 input 永远不会被填充,并且将包含您随后打印的随机数据.

With the pattern "%[A-Z]" you only scan for uppercase letters, and if the string you input doesn't begin with upper case letters scan will fail. This of course means that the string input will never be filled, and will contain random data which you then print.

我建议您阅读例如此参考.它会告诉您该函数将返回成功扫描的项目数,在您的情况下应该是 1.如果代码中的 scanf 函数没有返回 1,则说明存在问题.

I recommend you read e.g. this reference. It will tell you that the function will return the number of items successfully scanned, which should be 1 in your case. If the scanf function in your code doesn't return 1 then there is a problem.

所以你需要做类似的事情

So you need to do something like

if (scanf(...) == 1)
    printf(...);
else
    printf("Something went wrong when reading input\n");

这篇关于如何使用“scanf"输入特定的字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆