我希望逐行读取c中的文件并检查每一行是否为整数

时间:2018-05-22 15:06:09

标签: c file

如何逐行读取文件并检查每一行是否为整数?

FILE *fp;
fp = fopen("users.txt", "r");


while(fscanf(fp, "%d", &IDRead)!=EOF)
{
  enter code here
}

fclose(fp);

1 个答案:

答案 0 :(得分:1)

您可以使用fgets()读取一行,isdigit()检查字符串中的每个字符是否为数字。

首先,我们可以创建一个isnumber()函数来检查字符串中的每个字符是否都是数字。要处理负数,我们可以检查第一个字符是数字还是' - '。

bool isnumber(char* str) {
    int len = strlen(str);
    if (len <= 0) {
        return false;
    }

    // Check if first char is negative sign or digit
    if (str[0] != '-' && !isidigit(str[0])) {
        return false;
    }

    // Check that all remaining chars are digits
    for (int i = 1; i < len; i++) {
        if (!isdigit(str[i])) {
            return false;
        }
    }

    return true;
}

我们的isnumber()函数假定字符串没有前导或尾随空格,从fgets()检索的字符串可能同时包含两者。我们需要一个从字符串两端去掉空格的函数。您可以在this answer中了解如何执行此操作。

现在我们可以在while循环中使用我们的isnumber()函数来检查文件中fgets()的每一行。

FILE *fp = fopen("users.txt", "r");
if(!fp) {
    perror("Failed to open file");
    return -1;
}

const int MAX = 256;
char line[MAX];
while (fgets(line, MAX, fp) != NULL) {
    stripLeadingAndTrailingSpaces(line);
    printf("%s\t", line);

    if (isnumber(line)) {
        printf("is a number\n");
    }
    else {
        printf("is not a number\n");
    }
}

fclose(fp);