[問題] 統計字串中各數字個數

看板C_and_CPP (C/C++)作者 (閒雜人)時間16年前 (2009/10/08 22:22), 編輯推噓1(102)
留言3則, 3人參與, 最新討論串1/1
比如說輸入 1014587 輸出就是 0 :1 1 :2 2 :0 以此類推 但目前問題是if似乎沒作用 麻煩幫忙解題.. #include <iostream> #include <string> using namespace std; int main() { int i,n0=0,n1=0,n2=0,n3=0,n4=0,n5=0,n6=0,n7=0,n8=0,n9=0; char str[80]; cin.getline(str, 80); //cout<<strlen(str)<<"\n"; for(i=0;i<=strlen(str);i++) { if(str[i]==0) { n0=n0+1; } if(str[i]==1) { n1=n1+1; } if(str[i]==2) { n2=n2+1; } if(str[i]==3) { n3=n3+1; } if(str[i]==4) { n4=n4+1; } if(str[i]==5) { n5=n5+1; } if(str[i]==6) { n6=n6+1; } if(str[i]==7) { n7=n7+1; } if(str[i]==8) } n8=n8+1; } if(str[i]==9) { n9=n9+1; } } cout<<"0 : "<<n0<<"\n"; cout<<"1 : "<<n1<<"\n"; cout<<"2 : "<<n2<<"\n"; cout<<"3 : "<<n3<<"\n"; cout<<"4 : "<<n4<<"\n"; cout<<"5 : "<<n5<<"\n"; cout<<"6 : "<<n6<<"\n"; cout<<"7 : "<<n7<<"\n"; cout<<"8 : "<<n8<<"\n"; cout<<"9 : "<<n9<<"\n"; system("pause"); -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 211.73.173.145 ※ 編輯: assassinxcx 來自: 211.73.173.145 (10/08 22:26)

10/08 22:29, , 1F
'0'不等於0...
10/08 22:29, 1F

10/08 22:32, , 2F
已解答感謝 整個下午都是程式課 寫到昏頭了@@~
10/08 22:32, 2F

10/08 22:52, , 3F
把n0~n9用一個有10個int的陣列來作,number[str[i]-48]++;
10/08 22:52, 3F
文章代碼(AID): #1ApVMAz4 (C_and_CPP)
文章代碼(AID): #1ApVMAz4 (C_and_CPP)