繁体   English   中英

如何在C中将逗号分隔的行从文件拆分为变量?

[英]How to split a comma-delimited line from a file into variables in C?

如果我的文件的一行包含12,1 ,我该如何拆分数字并将它们放入2个变量? 例如,变量a将获得12 ,另一个变量b将获得1

第一种方法:

我们使用fscanf(),并放入我们期望文件具有的格式。 我们循环执行,直到函数的返回值小于我们期望读取的数字为止。

#include <stdio.h>

int main(void)
{
  FILE *fp;
  if ((fp = fopen("test.txt", "r")) == NULL)
  { /* Open source file. */
    perror("fopen source-file");
    return 1;
  }
  int a, b;
  while(fscanf(fp, "%d,%d", &a, &b) == 2)
  {
    printf("%d %d\n", a, b);
  }
  fclose(fp);
  return 0;
}

第二种方法:

我们将fgets()读入缓冲区,然后在strtok()的帮助下使用定界符(在本例中为逗号进行拆分。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define bufSize 1024

int main(void)
{
  FILE *fp;
  char buf[bufSize];
  if ((fp = fopen("test.txt", "r")) == NULL)
  { /* Open source file. */
    perror("fopen source-file");
    return 1;
  }
  char* pch;
  int a, b, i;
  while (fgets(buf, sizeof(buf), fp) != NULL)
  {
    i = 0;
    // eat newline
    buf[strlen(buf) - 1] = '\0';
    pch = strtok (buf,",");
    while (pch != NULL)
    {
      // read first number
      if(!i++)
        a = atoi(pch);
      else // read second number
        b = atoi(pch);
      pch = strtok (NULL, ",");
    }
    printf("%d %d\n", a, b);
  }
  fclose(fp);
  return 0;
}

该代码是基于在我的例子在这里


这两个示例都假定我们具有test.txt,如下所示:

1,2
3,4

PS-确保您下次下功夫。 :)

打开文件并成对解析文件。

int a, b;
freopen("input_file", "r", stdin);
while(scanf("%d,%d", &a, &b) == 2)
{   // do sth with a, b
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM