问题描述
- 循环到第二次时scanf函数会自动获取n,这个是为什么?
-
#include;
//#include
//#define PI 3.1415926
int main(void)
{
char letter=0;
while(1)
{
printf("Enter an upcase letter:");
scanf("%c",&letter);
if(letter>='A')
if(letter<='Z')
{
letter=letter-'A'+'a';
printf("You entered an uppercase %cn",letter);
}
else
printf("Try using the shift key,Bud!I want a capital letter.n");
else
printf("You didn't enter an uppercase letter.n");}; return 0;
};
解决方案
看 MSDN 的示例,应该不存在所描述的问题。难道是回车多按了一次?
/* SCANF.C: This program uses the scanf and wscanf functions
* to read formatted input.
*/
#include <stdio.h>
void main( void )
{
int i, result;
float fp;
char c, s[81];
wchar_t wc, ws[81];
printf( "nnEnter an int, a float, two chars and two stringsn");
result = scanf( "%d %f %c %C %s %S", &i, &fp, &c, &wc, s, ws );
printf( "nThe number of fields input is %dn", result );
printf( "The contents are: %d %f %c %C %s %Sn", i, fp, c, wc, s, ws);
wprintf( L"nnEnter an int, a float, two chars and two stringsn");
result = wscanf( L"%d %f %hc %lc %S %ls", &i, &fp, &c, &wc, s, ws );
wprintf( L"nThe number of fields input is %dn", result );
wprintf( L"The contents are: %d %f %C %c %hs %sn", i, fp, c, wc, s, ws);
}
Output
Enter an int, a float, two chars and two strings
71
98.6
h
z
Byte characters
The number of fields input is 6
The contents are: 71 98.599998 h z Byte characters
Enter an int, a float, two chars and two strings
36
92.3
y
n
Wide characters
The number of fields input is 6
The contents are: 456 92.300003 y n Wide characters
解决方案二:
全部输入打印出来对比一下
解决方案三:
好多人都会遇到这问题,因为scanf没读完所有缓存中的信息。把回车剩外面了,被下次的scanf接收到了。
时间: 2025-01-20 18:49:04