gpt4 book ai didi

c - 从文件中读取整数并忽略 C 中的空格

转载 作者:行者123 更新时间:2023-11-30 15:45:09 24 4
gpt4 key购买 nike

我正在学习 C,我用 C 编写的程序的一部分是检查我的 txt 文件包含的值是否少于或多于 81 个,以及所有值是否都是整数。我使用 fscanf 从文件中读取值,但它也会读取空格。如何忽略空格并使其只读整数或字符?

我的代码返回 162,其中包含 81 个整数和空格。

这是txt文件:

1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 1
3 4 5 6 7 8 9 1 2
4 5 6 7 8 9 1 2 3
5 6 7 8 9 1 2 3 4
6 7 8 9 1 2 3 4 5
7 8 9 1 2 3 4 5 6
8 9 1 2 3 4 5 6 7
9 1 2 3 4 5 6 7 8


#include<stdio.h>

int main() {
FILE * input_values;

input_values = fopen("text.txt","r");

if (input_values == NULL) {
fprintf(stderr, "Error! Could not open file.\n");
}

int ch, counter = 0;

ch = fscanf(input_values, "%d");
while (ch != EOF) {
counter++;
ch = fscanf(input_values, "%d");
}

printf("num %i",counter);
fclose(input_values);

}

最佳答案

您需要传入 fscanf 的输出变量,我很惊讶您的代码没有崩溃:

int num;
fscanf(input_values, "%d", &num);

如果您同时更改 fscanf,它会按预期工作

关于c - 从文件中读取整数并忽略 C 中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19205631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com