【问题标题】:Splitting string and storing into array (in C)拆分字符串并存储到数组中(在 C 中)
【发布时间】:2016-06-04 17:46:26
【问题描述】:

尝试将扫描到的字符串拆分到我的数组“行”中,其中新字符串由空格拆分,并且每个拆分字符串都应该进入我的数组“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;
}

【问题讨论】:

  • 示例输入和预期输出?
  • 抱歉,已发布。 4 无关紧要。现在只是一个任意数字。但是有示例字符串,它被拆分但无法将其存储在不同的索引中

标签: c string split strtok


【解决方案1】:
    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');

【讨论】:

  • 我不确定如何合并代码以忽略该行的其余部分
  • @Hispazn,只需在调用 scanf 之后添加这两行。
  • 它说“错误:函数'getc'的参数太少”
  • @Hispazn,我的错。我忘记在对getc 的调用中添加stdin
猜你喜欢
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
相关资源
最近更新 更多