gpt4 book ai didi

c - 如何从字符串中扫描未知数量的元素?

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:56 24 4
gpt4 key购买 nike

我试图从一个字符串中扫描多个整数,但我不知道它会有多少,因为它因情况而异。我想扫描多个数字并将它们放在一个数组中。

我一直在尝试这样做,但它不起作用......假设我想从字符串“line”中扫描 C 数字。

for(a=0;a<c;a++)
sscanf(line, " %d ",&v[a]);

最佳答案

我写了一段代码,帮助你更清楚地理解它。

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

int main(void){
int v[10];
char buffer[4096];

char * line = NULL;
int i, j;


if(fgets(buffer, 4096, stdin) == NULL){
return -1;
}

for(i = 0, line = strtok(buffer, " "); i < 10; i++){
if(line == NULL){
break;
}

sscanf(line, "%d", &v[i]);
line = strtok(NULL, " ");
}
j = i;

for(i = 0; i < j; i++){
printf("%d\n", v[i]);
}

return 0;
}

[neo]:./a.out
1 2 3 4 5 9999
1
2
3
4
5
9999

关于c - 如何从字符串中扫描未知数量的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15673326/

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