[問題] 計算字串中字元個數

看板C_and_CPP (C/C++)作者 (PPP)時間16年前 (2009/05/06 11:19), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串1/1
想請問一下 這是我自己寫的計算字串中程式字元個數程式 遇到了一些問題 我不太懂為什麼還要多一個黃色部分的getchar() 因為如果不加那一行 輸入字元顯示會有問題 另外紅色那一行也有個問題 印不出輸入字元 可以幫我看一下嗎? 順便指正我這個新手寫程式的壞習慣 #include <stdio.h> #include <stdlib.h> int main() { char string[100]; char InputChar; int i,j=0; printf("請輸入字串 (字串長度<100): "); scanf("%s",&string); printf("請輸入尋找字元: "); InputChar=getchar(); // 輸入字元 getchar(); /* 因為字元被讀取後還有個換行字元在緩衝區, 再用getchar()讀取換行字元以免發生錯誤 */ for(i=0;;i++) { if(string[i]==InputChar) j=j+1; else { if(string[i]=='\0') break; else continue; } } printf("字串 %s 中有 %d 個 %c 字元\n", string, j, InputChar); system("pause"); return 0 ; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.116.243.66

05/06 11:38, , 1F
InputChar=getchar();跟 getchar(); 要對調
05/06 11:38, 1F
文章代碼(AID): #1A0G6okn (C_and_CPP)
文章代碼(AID): #1A0G6okn (C_and_CPP)