发一个我自己的实现,感觉比作者的好,可以处理没有任何输入的情况.#include <stdio.h>
int addUserInput();
char letterToNumber(char last_letter, int* value, bool counter_to_zero);
int pow(int down, int up);
int main() {
int sum = addUserInput();
printf("%d", sum);
return 0;
}
int addUserInput() {
int sum = 0;//所有的总值
bool need_preread = true;
bool end_for = false;
char preread = ' ';
int value = 0;
for (;;) {
if (need_preread) {
preread = getchar();//在这里获取预读取值
}
else {
need_preread = true;
}
switch (preread) {
case ' ':
while ((preread = getchar()) == ' ');
need_preread = false;
break;
case '\n':
end_for = true;
break;
default:
preread = letterToNumber(preread, &value, true);
sum += value;
need_preread = false;
if (preread == '\n') {
end_for = true;
}
break;
}
if (end_for) {
break;
}
}
return sum;
}
char letterToNumber(char last_letter, int* value, bool counter_to_zero) {
char current_letter = getchar();
static int counter = 0;//当遇到空白字符时开始counter的增加,每次解开一层递归就计数器加1
if (counter_to_zero) {
counter = 0;
counter_to_zero = false;
}
static char flag = 'N';//返回N表示没有遇到空字符
if (current_letter >= '0' && current_letter <= '9') {//如果当前的字符为数字字符就继续执行letter_to_number
letterToNumber(current_letter, value, counter_to_zero);
}
else {
flag = current_letter;
}
*value += (last_letter - '0') * pow(10, counter);
counter++;
return flag;
}
int pow(int down, int up) {
if (up == 0) {
return 1;
}
else {
int sum = 1;
for (int i = 0; i < up; i++) {
sum *= down;
}
return sum;
}
}
|