【问题标题】:I want to read from file in c line by line and check each line if it is an integer我想逐行读取c中的文件并检查每一行是否为整数
【发布时间】:2018-05-22 15:06:09
【问题描述】:

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

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


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

fclose(fp);

【问题讨论】:

  • 好吧,在那里输入一些代码......
  • 你可以检查fopen的返回值
  • 还要检查 fscanf() 的返回值
  • 哦,顺便说一句,已经存在的代码不符合您的规范。不过,您应该显示完整的代码,请参阅minimal reproducible example
  • 如果您正在“逐行”处理文件,您不应该使用fgets 来“逐行”读取文件吗?

标签: c file


【解决方案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);

【讨论】:

  • 由于'\n'isnumber() 返回 false。由于前导空格或'+',也会返回false。
  • 注意:去除空格的referenced answer 具有技术上的 UB 和低效率以及 6 个反对票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 2018-02-06
相关资源
最近更新 更多