当 0 是行中的最后一个整数时,如何使用 C++ 检测你已经到达 fgets 整数字符串的末尾?

How to detect you've reached the end of a fgets string of integers, when 0 is the last integer in the line, using c++?

如果我从不同长度的 .txt 文件中读取行,(即第 1 行 5 个整数,然后第 2 行 2 个整数,然后第 3 行 10 个整数,等等),使用 fgets (虽然我不一定需要使用它,但在我的情况下似乎是一个很好的工具)。我发现每个解决方案 returns 错误为 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
}
}

您实际上可以使用 C++:

std::ifstream file("text.txt");
std::string line;
while (std::getline(file, line)) {
    std::istringstream iss(line);
    int i;
    while (iss >> i) {
        // ...
    }
}

内部循环可以简单地将所有整数直接加载到一个向量或其他东西中:

std::ifstream file("text.txt");
std::string line;
while (std::getline(file, line)) {
    std::istringstream iss(line);
    std::vector<int> all_the_ints{
        std::istream_iterator<int>{iss},
        std::istream_iterator<int>{}
    };
}

Ben的回答太好了,应该是答案的一部分

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

检查错误号。来自手册页

删除

结果值超出范围。 该实现还可以将 errno 设置为 EINVAL,以防未执行任何转换 (未看到数字,返回 0)

您正在丢弃 strtol 中可用的信息。

特别是打完电话后

val = strtol(p, &endp, radix);

您是否有兴趣p == endp

在你的调用中 strtol(p, &p, radix) 你覆盖 p 太早了,失去了执行测试的机会。