c - 如何在C中读取数字到字符串直到行尾

标签 c arrays file input eol

我有一个像这样的输入文件

10 25 4 3 86 1 23 20 14 1 3 7 3 16 7
2

第一行:数字数组。

第二行:整数k。

我尝试fgets()来读取它们,但它不起作用。这是我的代码:

int main(){
    FILE *input = fopen("Input7.txt","r");
    int a[2000],k;
    fgets(a,2000,input);
    fscanf(input,"%d",&k);
    fclose(input);
    int i,n;
    n = 15; //My example array have 15 numbers
    for (i=1;i<=n;++i){
        printf("%d  ",a[i]);
    }
    return 0;
}

我读完后打印出了数组 a,但这就是我得到的 Photo links

我该如何解决这个问题?顺便说一句,我想计算我读入数组的数量。感谢您的帮助。

最佳答案

您必须将 a 数组的类型更改为 char,因为 fgets等待 char* 作为第一个参数。

下一个重要的事情是,fgets 将字符读取到指定的 char 数组中,而不是直接读取数字,您必须对读取的字符序列进行标记并转换每个标记为整数。您可以使用 strtok 标记您的 a 数组。功能。

#include <stdio.h> // for fgets, printf, etc.
#include <string.h> // for strtok

#define BUFFER_SIZE 200

int main() {
    FILE* input = fopen("Input7.txt", "r");
    char a[BUFFER_SIZE] = { 0 };
    char* a_ptr;

    int k, i = 0, j;
    int n[BUFFER_SIZE] = { 0 };

    fgets(a, BUFFER_SIZE, input); // reading the first line from file
    fscanf(input, "%d", &k);

    a_ptr = strtok(a, " "); // tokenizing and reading the first token
    while(a_ptr != NULL) {
        n[i++] = atoi(a_ptr); // converting next token to 'int'
        a_ptr = strtok (NULL, " "); // reading next token
    }

    for(j = 0; j < i; ++j) // the 'i' can tell you how much numbers you have
        printf(j ? ", %d" : "%d", n[j]);
    printf("\n");

    fclose(input);
    return 0;
}

关于c - 如何在C中读取数字到字符串直到行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45101106/

相关文章:

c - 如何调用仅根据参数打印出语句的 C 函数

c++ - 在返回表达式中奇怪地使用 & 运算符

c - 如何暂停/恢复 Lua 命令的处理

java - 用于查找文件夹中丢失的文件编号的代码

将小写字母转换为大写字母

arrays - 如何匹配两个数组中相同的牌

c++ - 在 AVR 的程序内存中构建编译时任意长度数组

c - printf 命令导致段错误?

java - 加快文件读取

python - path.exists() 返回 False