[英]Code doesn't read the last character of string of Characters (C language)
#include "stdio.h"
int main() {
char input[10];
char standart;
int i;
int b = 0;
scanf("%c", &standart);
for(i = 0; i < 10; i++){
scanf("%c ", &input[i]);
if(input[i] == standart){
b++;
}
}
printf("%d", b);
return 0;
}
// ( 2 % a b ( r ) ? ( (
該代碼是后繼代碼,可讀取列表中的第一個字符,然后查看有多少個上述字符(不包括其自身)。 但是代碼不會讀取最后一個字符,總之,當我輸入示例輸入時,代碼只會看到2'(',而應該看到3。
對於給定的輸入( 2 % ab ( r ) ? ( (
,該程序采用第一個字符(
作為變量standart
輸入-
scanf("%c", &standart);
之所以會出現此問題,是因為在for
循環的第一次迭代中for
scanf
正在從給定的輸入中讀取第一個空格字符(空白) (
並將其存儲到input[0]
for
。for循環運行10次迭代,而最后一個字符(
未中插入input
,因為其中的陣列standart
在字符計數input
陣列即將一個小於預期,即2。
將for
循環scanf
語句更改for
-
scanf(" %c", &input[i]); //Removed the space after %c and added a space before %c.
這樣,for循環scanf
將吃掉空白字符。 所以,從輸入下一個字符- 2
將被存儲到input[0]
和%
將被存儲到input[1]
等和最后一個字符“(”將被存儲到input[9]
而且, b
將在input
數組中具有正確的standart
字符計數,即3。
您必須像scanf(" %c",&c);
因為它從先前的輸入中讀取了“ \\ n”,所以空格將跳過“ \\ n”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.