如何在 C 中对单个字符执行 scanf [英] How to do scanf for single char in C

查看:30
本文介绍了如何在 C 中对单个字符执行 scanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 中:我正在尝试使用 scanf 从用户那里获取字符,当我运行它时,程序不会等待用户输入任何内容......

In C: I'm trying to get char from the user with scanf and when I run it the program don't wait for the user to type anything...

这是代码:

char ch;
printf("Enter one char");
scanf("%c", &ch);
printf("%c
",ch);

为什么不起作用?

推荐答案

%c 转换说明符不会自动跳过任何前导空格,因此如果输入流中有一个杂散的换行符(从前一个条目,例如)scanf 调用将立即使用它.

The %c conversion specifier won't automatically skip any leading whitespace, so if there's a stray newline in the input stream (from a previous entry, for example) the scanf call will consume it immediately.

解决该问题的一种方法是在格式字符串中的转换说明符之前放置一个空格:

One way around the problem is to put a blank space before the conversion specifier in the format string:

scanf(" %c", &c);

格式字符串中的空白告诉 scanf 跳过前导空格,第一个非空格字符将使用 %c 转换说明符读取.

The blank in the format string tells scanf to skip leading whitespace, and the first non-whitespace character will be read with the %c conversion specifier.

这篇关于如何在 C 中对单个字符执行 scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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