2012-11-05 24 views
1

我有一个字符串input,其中包含由空格分隔的单词。我想用sscanf()拆分单词,将每个单词存储在input_word中并打印出来,但我不确定如何将它放在while循环中。sscanf()在C中的while循环中

这是我有:

char input[max]; 
char split_input[max]; 

/* input gets populated here */ 

while (sscanf(input," %s", split_input)) { 
    printf("[%s]\n", split_input); 
} 

什么会尽快序列中的最后一个字拆终止循环的条件?

+1

见[strtok的()](http://www.cplusplus.com/reference/clibrary/cstring/strtok/) – WhozCraig

+0

@dasblinkenlight时,'scanf'家庭返回'上输入的端EOF'。据我所知,这一直被定义为-1,尽管可能有不同的平台来定义它。 –

回答

4

你在那里使用了错误的功能。我可以建议strtok()而不是?

这里阅读strtok

3

也许不能覆盖所有角落的情况。

#include <stdio.h> 

int main(void) 
{ 

    char *input = "abc def ghi "; 
    char split_input[sizeof input]; 
    int n; 

    while (sscanf(input," %s%n", split_input, &n) == 1) { 
     printf("[%s]\n", split_input); 
     input += n; 
    } 
} 
0

我也建议strtok()功能。它标记了你的字符串,并允许你在一个循环内逐个提取单词。这是一个例子,假设input是你定义的字符串,我写了一个这样的函数。

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

int tokenize(char *input) { 

    const char space[2] = " "; 
    char *token = strtok(input, space); 
    while (token != NULL) { 
     token = strtok(NULL, space); 
     printf("%s\n", token); 
    } 

    return 0; 
}