【问题标题】:How to read number to string till end of the line in C如何在C中读取数字到字符串直到行尾
【发布时间】:2017-12-19 10:40:48
【问题描述】:

我有一个这样的输入文件

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

第一行:一个数字数组。

第 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

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

【问题讨论】:

  • 您能否详细说明“它不起作用”部分?
  • 也许会一直做minimal reproducible example
  • fgets() 是读取一个字符串,它需要一个 char*,而不是 int*。您需要读取字符串,然后解析字符串以填充您的 int[]。
  • 编译该代码时没有收到任何错误或警告吗?您的数组 a 不是与 fgets 一起使用的正确类型
  • 如果你看 fgets 的原型,第一个参数是 char*,但你提供的是 int[]。尝试修复警告(不使用强制转换)。他们在那里是有原因的。

标签: c arrays file input eol


【解决方案1】:

您必须将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++);尽管如果在没有-pedantic 的情况下调用它,gcc 会接受它。有效的“通用零初始化器”是{0}
  • @pmg,感谢您的澄清。是的,它在 C++ 中有效。
【解决方案2】:

忽略线的东西...

继续阅读数字直到 EOF

int array[1000];
int k = 0;
int prev, last;
if (scanf("%d", &prev) != 1) /* error */;
while (scanf("%d", &last) == 1) {
    array[k++] = prev;
    prev = last;
}
// array has the k numbers in the first line
// prev has the single number in the last line

如果需要,可以使用 malloc()realloc()free() 使数组动态化。

【讨论】:

  • 感谢您的帮助
猜你喜欢
  • 2014-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 2015-03-11
  • 1970-01-01
相关资源
最近更新 更多