gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:46:00 26 4
gpt4 key购买 nike

我正在用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com