如何在C单个字符做scanf函数 [英] How to do scanf for single char in C

查看:129
本文介绍了如何在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...

这是code:

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

为什么不工作?

推荐答案

%C 转换符不会自动跳过任何前导空格,所以如果有一个流浪换行符在输入流(从previous条目,例如)在 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天全站免登陆