使用%c 奇数循环不起作用
我倾向于C编程。 我写了一个奇怪的循环,但在scanf()
使用%c
不起作用。
这是代码:
#include void main() { char another='y'; int num; while ( another =='y') { printf("Enter a number:\t"); scanf("%d", &num); printf("Sqare of %d is : %d", num, num * num); printf("\nWant to enter another number? y/n"); scanf("%c", &another); } }
但是如果我在这段代码中使用%s
,例如scanf("%s", &another);
,然后它工作正常。
为什么会这样? 任何的想法?
%c
转换从输入读取下一个单个字符,无论它是什么。 在这种情况下,您之前使用%d
读取了一个数字。 您必须按Enter键才能读取该数字, 但您还没有做任何事情来从输入流中读取新行。 因此,当您执行%c
转换时,它会从输入流中读取该换行符(无需等待您实际输入任何内容,因为已经有输入等待读取)。
使用%s
,它会跳过任何前导空格以获得除空白之外的某些字符。 它将新行视为空白行,因此它会隐含地跳过等待的新行。 因为(大概)没有别的东西等着被读,所以它会等着你输入一些东西,就像你显然想要的那样。
如果要使用%c
进行转换,可以在格式字符串前面加一个空格,这也会跳过流中的任何空白区域。
输入第一个scanf%d的数字后,ENTER键位于stdin流中。 该键由scanf%c行捕获。
使用scanf("%1s",char_array); another=char_array[0];
scanf("%1s",char_array); another=char_array[0];
。
在这种情况下使用getch()
而不是scanf()
。 因为scanf()需要’\ n’但你只接受scanf()上的一个char。 所以’\ n’给下一个scanf()导致混乱。
#include void main() { char another='y'; int num; while ( another =='y') { printf("Enter a number:\t"); scanf("%d", &num); printf("Sqare of %d is : %d", num, num * num); printf("\nWant to enter another number? y/n"); getchar(); scanf("%c", &another); } }