如果我正在从长度可变的.txt文件中读取行(例如,第1行中有5个整数,然后在第2行中有2个整数,然后在第3行中有10个整数,依此类推),则使用fgets(尽管我不这样做)不一定需要使用它,就我而言,这似乎是一个很好的工具)。我找到的每个解决方案都返回错误0(如strtol或atio)。

char str[100];
char* p = str;
FILE* fp;
fp = open("text.txt",r);
if(fp == NULL)
    printf("aborting.. Cannot open file! \n");
while(!foef(fp))
{
if(fgets(p,100,fp) != NULL)
{
    for (int j = 0 ; j < 20 ; j+=2)
    {
        temp1 = strtol(p, &p, 10);
        // need to store temp1 into arr[j] if it is a valid integer (0->inf)
        // but should discard if we are at the end of the line
}
}

最佳答案

本的答案很好,应该成为答案的一部分

在调用strtol之前将errno设置为0。

检查errno。从手册页

范围

所得值超出范围。
如果未执行转换,则实现也可以将errno设置为EINVAL (未看到数字,并且返回0)

10-07 19:32
查看更多