【发布时间】:2011-04-23 04:52:30
【问题描述】:
我正在尝试编写一个程序,该程序将纯文本文件作为参数并对其进行解析,将所有数字加在一起,然后打印出总和。以下是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
static int sumNumbers(char filename[])
{
int sum = 0;
FILE *file = fopen(filename, "r");
char *str;
while (fgets(str, sizeof BUFSIZ, file))
{
while (*str != '\0')
{
if (isdigit(*str))
{
sum += atoi(str);
str++;
while (isdigit(*str))
str++;
continue;
}
str++;
}
}
fclose(file);
return sum;
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "Please enter the filename as the argument.\n");
exit(EXIT_FAILURE);
}
else
{
printf("The sum of all the numbers in the file is : %d\n", sumNumbers(argv[1]));
exit(EXIT_SUCCESS);
}
return 0;
}
我使用的文本文件是:
这是一个相当无聊的文本文件 一些散落的随机数 贯穿其中。
这是一个:87,这是另一个:3
最后两个数字:12 19381. 完成。唷。
当我编译并尝试运行它时,我遇到了分段错误。
【问题讨论】:
标签: c arrays pointers segmentation-fault