c - 拆分字符串并存储到数组中(在 C 中)

标签 c string split strtok

尝试将扫描到的单词字符串拆分到我的数组“line”中,其中新字符串被一个空格拆分,每个拆分字符串都应该进入我的数组“scoops”,这样我就可以访问任何拆分字符串索引稍后

但我无法让它完全工作。当我尝试在 while 循环内打印 scoops 数组时,由于某种原因,j 索引保持为 0,但正确打印了拆分字符串。

当我试图在 while 循环之外查看所有新字符串时,它只打印索引 0 的第一个字符串。之后崩溃。

示例输入/输出: enter image description here

(我尝试搜索类似的帖子并尝试了这些解决方案,但仍然出现同样的问题)

#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');

关于c - 拆分字符串并存储到数组中(在 C 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35568231/

相关文章:

c - 当用户在保持 float 变量的 scanf 中输入字符串时出错

Java - split(regex, limit) 方法实际上如何工作?

xcode - 核心数据 - 无法将空字符串设置为属性的默认值

C 编程 strchr 返回指针

c++ - 为什么使用 'function address == NULL' 而不是 'false' ?

c - 是否可以在 Lua 中禁用堆栈回溯?

java - 字符串将空值拆分到数组中以使用 if 语句

r - 将数据集划分为 60%、20%、20%

c - 帮助优化函数循环获取文件大小

JavaScript split() join() 仅适用于精确短语