c - 将具有未知数量元素的字符串扫描到 C 中的 int 数组

标签 c arrays string strtok scanf

我正在用 C 编写一个程序,我有一个数字字符串,如下所示:

5 13 12 7 3 0

我想扫描它并将这些整数中的每一个放入一个 int 数组中。我怎么做? 这是为此使用 sscanf 的一种方式吗?

我尝试了以下代码但没有成功:

 fgets(datatemp, N*3, stdin);

 k = 0; garb = 'c';
    while(garb != '\0'){
      garb = strtok(datatemp, " ");
      array[k] = garb;
      k++;
    }

注意:我必须在一个函数中使用它,该函数将对许多数据执行相同的操作,其中“datatemp”字符串将具有未知数量的整数(并且只有整数)。

感谢您的帮助。

最佳答案

// Adapted from strtok(3) example.

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

int
main(int argc, char *argv[])
{
  char *str1, *str2, *token, *subtoken;
  char *saveptr1,*saveptr2;
  int j;
  char datatemp[ 120 ];
  char delim = ' ';

  fgets(datatemp, 119, stdin);

  /*
   * strtok has to be called with a pointer to the input
   * the first time then with a pointer to the string
   * subsequently
   */

  for(j=1, str1 = datatemp;; j++, str1 = NULL)
  {
    token = strtok_r(str1, &delim, &saveptr1);

    if(token==NULL)
      break;

    for (str2 = token; ; str2 = NULL)
    {
      subtoken = strtok_r(str2, &delim, &saveptr2);
      if (subtoken == NULL)
        break;
      printf(" --> %s\n", subtoken);
    }
  }

  exit(0);

关于c - 将具有未知数量元素的字符串扫描到 C 中的 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24364080/

相关文章:

复制字符串函数在 C 中不起作用

编译C代码: error: lvalue required as left operand of assignment

c - 问题 - 首先按频率对字符串中的字符进行排序

java - 关于 JAVA 单词顺序反转的基本 Java 编码问题

sql - 如何使用 GROUP BY 连接 MySQL 中的字符串?

c - 将函数输入到链表中

c - 如何用 C 语言编写 Hello World

c - 多维数组和指向具有一个 Typedef 的数组的指针

arrays - 如何从两个列表中快速打印

javascript - 使用 const 创建动态变量