[英]unexpected output of the following c program
下面的代碼按預期應接受來自用戶的兩個char值。 但是它只接受ch1的一個值,然后輸出“ hello”。
#include<stdio.h>
int main()
{
char ch1, ch2;
printf("Enter a char: ");
scanf("%c",&ch1);
printf("Enter second char: ");
scanf("%c",&ch2);
printf("Hello");
return 0;
}
它不接受ch2的第二個值。可能是什么原因? 據我認為,它應該接受2個字符。
它僅接受一個字符,因為對scanf()
的第一次調用在輸入流中留下了換行符。
您可以使用以下方法忽略它:
scanf(" %c",&ch2); // note the leading space.
這將確保來自先前輸入的換行符將被忽略。 格式字符串中的空格告訴scanf()
忽略任意數量的空格字符。 您可能還需要檢查scanf()
調用的返回值,以防失敗。
從scanf()
:
. A sequence of white-space characters (space, tab, newline,
etc.; see isspace(3)). This directive matches any amount of
white space, including none, in the input.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.