輸入字串(如 "a1b23c"),提取其中所有數字字元('1','2','3'),轉為整數並累加(1+2+3=6)。
字元 '0'~'9' 在 ASCII 碼中連續排列,'0'=48, '1'=49, ..., '9'=57。故 ch - '0' 即得對應整數值。
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char shu[100];
cout << "請輸入字串: ";
cin >> shu;
int sum = 0;
int len = strlen(shu);
for (int i = 0; i < len; i++) {
if (shu[i] >= '0' && shu[i] <= '9') {
sum += shu[i] - '0';
}
}
cout << "sum=" << sum << endl;
return 0;
}
shu[i] - '0':字元減去字元,結果為 int,自動提升參與加法。strlen 需 <cstring>;C++ 建議改用 std::string 避免緩衝區溢位。isdigit 與 std::string#include <string>
#include <cctype>
string s; cin >> s;
int sum = 0;
for (char c : s) if (isdigit(c)) sum += c - '0';
掌握字元與整數的 ASCII 對應關係,是字串處理數字的基礎技巧。