【发布时间】:2012-06-07 18:01:11
【问题描述】:
晚上好,
我在分配作业时遇到问题。
基本上,我们需要编写一个程序来计算给定stdin 的质因数。数据只能通过stdin 进入程序,无论是echo 还是< file.txt。数据流永远不会超过 80 个字符(它们可以是数字,也可以不是数字)。
我在程序中使用的函数是read()、strotol()和strtok(),“无关”的代码流程如下:
- 使用
malloc分配80 个初始字节的内存。 - 将读取的字符数存储在
int到read()(我相信是最后一个\0)。 - 用
realloc()重新分配内存以节省尽可能多的内存(我知道在这种情况下这很简单,但是哦……)。
现在是棘手的一点:
- 由于数据必须用空格隔开,所以要检查的最大项目数为:
(n/2)+1,其中n是在上点nº2读取的字符数。 - 创建一个
long数组,其最大大小为在第 1 点获得的数字。 - 用
strtol(strtok(line, delim), &end, 10)的结果填充numbers[0]。 -
将
1添加到counter并进入while循环:while((numbers[counter] = strtol(strtok(NULL, delim), &end, 10)) != NULL) { if(!*end) { // Check whether it's 0, 1, negative, prime or extract its factors } else { fprintf(stderr, "\"%s\" is not a non-negative integer", end) } counter++; }
现在,这里有一些输入和它们的输出:
输入:echo 1 2 3 4 5 6 7 8 9 10 | ./factors
输出:
1
2
3
2 2
5
2 3
7
2 2 2
3 3
2 5
Segmentation Fault (core dumped).
输入./factors < integers.txt
其中 integers 包含一列整数。
输出:
所有的整数都被分解得很好,最后打印出一个:
Segmentation Fault (core dumped).
输入:echo abc 12 13 14 15 | ./factors
输出:
"abc" is not a non-negative integer
13
2 7
3 5
Segmentation Fault (core dumped).
输入:echo -1 -2 -3 -4 -5 | ./factors
输出:
"-1" is not a non-negative integer
"-2" is not a non-negative integer
"-3" is not a non-negative integer
"-4" is not a non-negative integer
"-5" is not a non-negative integer
输入:echo abc abc abc | ./factors
输出:
"abc" is not a non-negative integer
(并且不继续检查)。
输入:echo 3 4 0 6 7 | ./factors
输出:
3
2 2
(并且不继续检查)。
据我所知,当遇到0、多个非integer 实例或基本上在基于integer 的健康数据流的末尾时,它会失败。
知道我该如何解决这个问题,为什么它会如此明显地随机失败?
我应该让你知道我是 C 新手...
非常感谢您。
================================================ =====
EDIT1:根据要求,这里是生成numbers[]的代码片段,并从stdin读取:
char *line;
char *end;
char *delim = " \n";
int charsread, counter;
line = malloc(80);
charsread = read(0, line, 81);
if (charsread == 0) {
return EX_OK;
}
realloc(line, charsread);
maxelem = (charsread / 2) + 1;
long numbers[maxelem];
numbers[0] = strtol(strtok(line, delim), &end, 10);
if (!*end) {
zeroone(numbers[0]);
}
else {
fprintf(stderr, "\"%s\" is not a non-negative integer\n", end);
}
counter = 1;
while [...]
【问题讨论】:
-
当
Input: echo abc abc abc | ./factors,strtol发生错误(并转换结果== 0)返回0,while(... != NULL)break while循环。 -
在
"abc" is not a non-negative number和13之间的第二个示例中是否也缺少一行?这是一个实际错误,还是仅仅来自您的重新转录? -
另外,
zeroone是做什么的???