数字总和缓冲区溢出
Sum of digits buffer overflow
我是 C 语言编程的新手,我正在寻找特定问题的解决方案。我必须创建一个程序来对数字求和。我所做的并不完美,但代码一直有效,直到字符串不像 stdin 中的 10000 位数字那么长,我被这个问题困住了。我不能输入所有这些数字,因为我会溢出。我想,我应该创建某种缓冲区,但我不知道如何从标准输入中创建它。谢谢你的任何想法。 (我很抱歉我的英语,它并不完美)
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
long a;
long value;
long c;
char s[10000];
printf("Input an integer\n");
scanf("%s", s);
value = a = 0;
while (s[a] != '[=10=]') {
c = s[a] - '0';
value = value + c;
a++; }
if(value < 10){
printf("Sum of digits %ld\n", value);}
while(value >= 10){
long digit = 0;
long value2 = 0;
while (value > 0)
{
digit = value % 10;
value2 = value2 + digit;
value /= 10;}
printf("Sum of digits %ld \n",value2); }
return 0;
}
您不需要缓冲区,因为您可以即时计算总和:
#include <stdlib.h> // EXIT_FAILURE
#include <stdio.h>
#include <ctype.h> // isdigit()
int main()
{
puts("Input an integer:");
long long unsigned sum = 0;
for (int ch = fgetc(stdin); ch != EOF && ch != '\n'; ch = fgetc(stdin)) {
if (isdigit(ch)) {
sum += (ch - '0');
}
else {
fprintf(stderr, "'%c' is not a valid digit :(\n\n", ch);
return EXIT_FAILURE;
}
}
printf("Sum of digits: %llu\n\n", sum);
}
我是 C 语言编程的新手,我正在寻找特定问题的解决方案。我必须创建一个程序来对数字求和。我所做的并不完美,但代码一直有效,直到字符串不像 stdin 中的 10000 位数字那么长,我被这个问题困住了。我不能输入所有这些数字,因为我会溢出。我想,我应该创建某种缓冲区,但我不知道如何从标准输入中创建它。谢谢你的任何想法。 (我很抱歉我的英语,它并不完美)
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
long a;
long value;
long c;
char s[10000];
printf("Input an integer\n");
scanf("%s", s);
value = a = 0;
while (s[a] != '[=10=]') {
c = s[a] - '0';
value = value + c;
a++; }
if(value < 10){
printf("Sum of digits %ld\n", value);}
while(value >= 10){
long digit = 0;
long value2 = 0;
while (value > 0)
{
digit = value % 10;
value2 = value2 + digit;
value /= 10;}
printf("Sum of digits %ld \n",value2); }
return 0;
}
您不需要缓冲区,因为您可以即时计算总和:
#include <stdlib.h> // EXIT_FAILURE
#include <stdio.h>
#include <ctype.h> // isdigit()
int main()
{
puts("Input an integer:");
long long unsigned sum = 0;
for (int ch = fgetc(stdin); ch != EOF && ch != '\n'; ch = fgetc(stdin)) {
if (isdigit(ch)) {
sum += (ch - '0');
}
else {
fprintf(stderr, "'%c' is not a valid digit :(\n\n", ch);
return EXIT_FAILURE;
}
}
printf("Sum of digits: %llu\n\n", sum);
}