[英]Could someone please why this program is not running correctly. I'm new to C
[英]i cant get this program to work correctly.
我被要求修改程序以讀取字符而不是數字。 我將數組修改為char數組。 如下將兩個“%d”更改為“%c”
void main(void){
char a[100];
int counter;
int b;
counter = 0;
printf("please enter the length of the array: ");
scanf("%d", &b );
while (counter != b)
{
printf("please enter character: ");
scanf("%c", &a[counter]);
counter++;
}
a[counter] = '\0' ;
counter = 0;
while (a[counter] != '\0')
{
printf("\n");
printf("%c",a[counter]);
counter++;
}
}
請輸入數組的長度:(4)
請輸入字符:請輸入字符:(a)
請輸入字符:請輸入字符:(a)
一種
一種
()用於指示用戶輸入。
如果我能得到一些幫助,那將是非常好的。
您必須記住, scanf
將換行符留在輸入緩沖區中,因此當您嘗試讀取字符時,它將換行。
解決方案非常簡單:通過在格式代碼中添加空格,告訴scanf
讀取和丟棄前導空白:
scanf(" %c", &a[counter]);
/* ^ */
/* | */
/* Note space here */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.