我試圖編寫一個程序,它接受一個純文本文件作爲它的參數並解析它,將所有數字加在一起,然後打印出總和。下面是我的代碼:爲什麼我會收到分段錯誤?
#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.完成。唷。
當我編譯並嘗試運行它時,出現分段錯誤。
嘿感謝現在的工作。但如果你不介意再忍受一段時間。如果在修復程序後嘗試運行程序,出於某種原因'atoi()'將數字'19381'分別解析爲'193'和'81'。任何想法爲什麼發生這種情況 – jon2512chua 2010-10-09 15:41:20
@Jon:更新了答案:) – codaddict 2010-10-09 15:57:22
Owh我現在看到了,謝謝! :) – jon2512chua 2010-10-09 16:12:23