【问题标题】:How to split a char array into two diferent types in c?如何在c中将char数组拆分为两种不同的类型?
【发布时间】:2021-06-15 23:47:41
【问题描述】:

所以,我需要使用标准输入来读取一个有两列的文件,第一列是字符,第二列是整数。

输入文件是这样的:

i 10
i 20
i 30
i 40
i 50
i 45
r 48

我目前的代码:

int main(){
    char line[MAX];
    int n = 0;
    while(fgets(line, MAX, stdin)){
            printf("string is: %s\n",line);

    }
    return 0;

输出结果为:

string is: i 10

string is: i 20

string is: i 30

string is: i 40

string is: i 50

string is: i 45

string is: r 48
 

所以,我现在需要做的是为第一列分配一个 char 数组,为第二列分配一个整数数组。像 int V[size] = [10,20,30,40,50,45,48] 和 char W[size] = [i,i,i ,i,i,i,r]。我该怎么做?

【问题讨论】:

  • sscanf() 应该是你要找的。​​span>
  • 使用sscanfstrtok。还建议您做一些研究,因为在 SO 和网络上有很多关于如何在 C 中解析字符串的帖子。

标签: arrays c string stdin


【解决方案1】:

使用sscanf()解析字符串,提取你想要的数据。

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

#define MAX 500

int main(void)
{
  int num[MAX] = {0}, lines = 0;
  char line[MAX] = {0}, sym[MAX] = {0};

  while (fgets(line, MAX, stdin))
  {
    if (lines >= MAX) /* alternative check comments */
    {
      fprintf(stderr, "arrays full\n");
      break; /* break or exit */
    }

    if (sscanf(line, "%c %d", &sym[lines], &num[lines]) != 2) /* check return value for input error */
    {
      /* handle error */
      exit(EXIT_FAILURE);
    }

    lines++;
  }

  for (int i = 0; i < lines; i++)
  {
    printf("char: %c | num: %d\n", sym[i], num[i]);
  }

  exit(EXIT_SUCCESS);
}

您还可以使用feof()ferror() 来确定@​​987654325@ 是否失败或您已达到EOF

【讨论】:

  • 干得好。替代while (lines &lt; MAX &amp;&amp; fgets(line, MAX, stdin)) { ... }。你所拥有的并没有错。感谢完整的验证。
  • 谢谢!我会将其添加为侧节点。
猜你喜欢
  • 2012-05-08
  • 2014-07-31
  • 2012-02-25
  • 2017-10-27
  • 2011-08-16
  • 2013-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多