2017-10-19 112 views
0

为什么在阅读一个单词后出现分词错误?如何使用strtok将用户输入的单词分隔符分隔为空格

如果我输入“这是为什么不行”

我只拿回

为什么

,然后我得到一个分段错误。

我见过其他的例子,但没有使用用户输入,我想在这里做。我只能读一个字,它不会工作。我尝试将%c全部更改为%s,但它不能帮助我。我也意识到分段错误是指向不在内存中的某个地方的指针,但我看不出它有什么问题。请帮助我理解。

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

int main() 
{ 
    char word[100]; 

    printf("Enter a sentence: "); 
    scanf("%s", word); 

    char *tok = strtok(word, " "); 
    printf("%s\n", tok); 

    while(tok != NULL) 
    { 
     tok = strtok(NULL, " "); 
     printf("%s\n", tok); 

     if(tok == NULL) 
      printf("finished\n"); 
    } 

    return 0; 
} 

编辑:我改变了scanf(“%s”,单词); fgets(单词,100,stdin);现在它可以打印所有内容,但是出现分段错误。

+1

'scanf(“%s”,单词);''不会在word中保存空格,只保存'why'。使用'fgets()'。 – chux

+0

@chux thanks dude我把它改成fgets(word,100,stdin),但我仍然遇到了段错误。 – Anonymous

+1

提示:为什么代码执行'printf(“%s \ n”,tok);'和_then_检查if'(tok == NULL)...'? – chux

回答

2

正如注释中指出的那样,第一个代码中至少有两个问题。

  1. 请勿使用scanf来读取要解析的字符串。改为使用fgets

  2. 你不测试tok不为空使用它(里面的while环)

这些问题会与调试已经很容易地检测过,所以我建议你阅读how to debug small programs

更正的代码应该是这样的:

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

int main(void) 
{ 
    char word[100]; 

    printf("Enter a sentence: "); 
    /* read from stdin 
     note the `sizeof char`, if you need to change the size of `word`, 
     you won't have to change this line. */ 
    fgets(word, sizeof word, stdin); 

    /* initialize parser */ 
    char *tok = strtok(word, " "); 

    while (tok != NULL) 
    { 
     /* printf token: it cannot be NULL here */ 
     printf("%s\n", tok); 

     /* get next token*/ 
     tok = strtok(NULL, " "); 
    } 
    printf("finished\n"); 

    return 0; 
} 
+1

建议声明'char * delim =“\ n”;'然后'char * tok = strtok(word,delim);'(在整个过程中使用'delim'进行类似的更改)。 –

0

此代码不正确

while(tok != NULL) 
{ 
    tok = strtok(NULL, " "); 
    printf("%s\n", tok); 

    if(tok == NULL) 
     printf("finished\n"); 
} 

假设你最后一次循环....它进入你上一次获得环....所以你让一个tok = strtok(NULL, " ");返回(及受让人)NULL因为有没有更多的东西....那么你printf(3)它,这产生了seg故障。

只需将其更改为此,如果没有更多标记可用,则不会进入循环。

while((tok = strtok(NULL, " ")) != NULL) 
{ 
    printf("%s\n", tok); 

    /* you don't touch tok inside the loop, so you don't need to 
    * test it again once you get inside */ 
} 

/* if(tok == NULL) <-- you always have tok == NULL here */ 
printf("finished\n"); 

或简单

while(tok = strtok(NULL, " ")) 
{ 
    printf("%s\n", tok); 
} 
printf("finished\n"); 

此外,添加\nstrtok(3)调用的第二个参数(在你在你的上市,在这两个电话,你只能有一个令牌,和最后一行结局必须从第一掉话),因为当你使用fgets(3)你通常会在字符串的结尾得到\n(你不希望):

char *tok = strtok(word, " \n"); 
printf("%s\n", tok); 

while(tok = strtok(NULL, " \n")) 
{ 
    printf("%s\n", tok); 
} 
printf("finished\n"); 
相关问题