[英]Splitting string and storing into array (in C)
尝试将扫描到的单词字符串拆分到我的数组“行”中,其中新字符串用空格拆分,每个拆分后的字符串都应该放入我的数组“ scoops”中,以便以后可以访问任何拆分后的字符串索引
但我无法使其完全正常运行。 当我尝试在while循环中打印scoops数组时,由于某种原因,j索引保持为0,但正确打印了分割字符串。
当我尝试在while循环之外查看所有新字符串时,它仅显示索引0的第一个。此后崩溃。
(我尝试搜索类似的帖子并尝试了这些解决方案,但仍然出现相同的问题)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int i,c,j;
char* order;
char line[256]; //max order is 196 chars (19 quadruples + scoop)
char* scoops[19]; //max 19 different strings from strtok
// get number of cases
scanf("%d",&c);
// do number of cases
for(i=0;i<c;i++){
scanf("%s", &line); //temp hold for long string of qualifiers
order = strtok(line, " "); //separate all the qualifiers 1 per line
j = 0;
while(order != NULL){
scoops[j] = order;
printf("scoops[%d] = %s\n",j,scoops[j]);
order = strtok(NULL, " ");
j++;
}
// checking to see if array is being correctly stored
//for(i=0;i<19;i++)
//printf("scoops[%d] = %s\n",i,scoops[i]);
}
return 0;
}
scanf("%s", &line); //temp hold for long string of qualifiers
不读取任何空格字符。 如果要阅读一行文本,包括空格字符,则需要使用fgets
。
fgets(line, sizeof(line), stdin);
但是,要执行此操作,您需要添加一些代码,这些代码将忽略在调用以下命令后输入流中剩余的其余行:
scanf("%d",&c);
如:
// Ignore the rest of the line.
char ic;
while ( (ic = getc(stdin)) != EOF && ic != '\n');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.