【问题标题】:Read only values from txt file只读 txt 文件中的值
【发布时间】:2018-05-15 13:35:34
【问题描述】:

我正在尝试从 txt 文件中读取变量。 文件 .txt 是这样的:

john 10
mark 230
peter 1

我想将这些值传输并保存在一个数组中,例如 array[0] = 10、array[1] = 230 等,而不考虑名称。我在下面粘贴了我的代码,我想知道如何使用下面的代码编辑它

int conf[4], i = 0, c;
FILE *file_conf;
file_conf = fopen("conf.txt", "r");

if(file_conf == NULL){
   fprintf(stderr, "Error\n");
   exit(EXIT_FAILURE);
} else {
    while((c = fgetc(file_conf)) != EOF) { 
        fscanf(file_conf, "%d", &conf[i]);
        printf("%d\n", conf[i]);
        i++; 
    }
}   

【问题讨论】:

    标签: c arrays parsing variables


    【解决方案1】:

    你根本不应该使用fgetc()——它只得到一个字符。相反,将名称格式添加到您的fscanf(),如下所示:

    char name[100];
    fscanf(file_conf, "%s %d", name, &conf[i]);
    

    【讨论】:

      【解决方案2】:

      您可以在 scanf() 系列转换说明符前面加上 * 以禁止分配。请注意,在发布的代码中,未能检查从 fscanf() 返回的值可能会导致输入格式错误的问题。此外,当数组索引i 增长太大以避免缓冲区溢出时,应该退出输入循环。当i 太大或遇到格式错误的输入时,以下代码会退出循环:

      #include <stdio.h>
      #include <stdlib.h>
      
      int main(void)
      {
          int conf[4], i = 0;
          FILE *file_conf;
          file_conf = fopen("conf.txt", "r");
      
          if(file_conf == NULL){
              fprintf(stderr, "Error\n");
              exit(EXIT_FAILURE);
          } else {
              while(i < 4 && fscanf(file_conf, "%*s%d", &conf[i]) == 1) {
                  printf("%d\n", conf[i]);
                  i++; 
              }
          }
      
          fclose(file_conf);
      
          return 0;
      }
      

      使用发布的示例输入进行输出:

      10
      230
      1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-06
        • 2018-01-11
        • 1970-01-01
        • 1970-01-01
        • 2018-05-25
        • 1970-01-01
        • 1970-01-01
        • 2012-12-17
        相关资源
        最近更新 更多