#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char token[20][256];
char input[256];
char *ctmp;
int i = 1, cnt = 1;
printf("$");
scanf("%s", input);
ctmp = strtok(input, " ");
while (ctmp != NULL) {
strcpy(token[cnt++], ctmp);
ctmp = strtok(NULL, " ");
}
while (i < cnt) {
printf("%s\n", token[i]);
i++;
system("pause");
}
return 0;
}
我正在尝试编写一个程序,可以将句子中的“”划分为标记。 但它只适用于第一个词而不是第二个词..
为什么会这样?我做错了什么吗?
最佳答案
scanf
读入直到空白,所以你应该使用 fgets
读到行尾(或 EOF,以先出现者为准),所以它应该是:
fgets(input, sizeof input, stdin);
(有关更多详细信息,请查看 http://en.cppreference.com/w/c/io/fgets)
您读取的行也可能比缓冲区能够容纳的更长,因此您可能需要一个额外的循环来获取整行并相应地调整缓冲区的大小,或者逐 block 迭代地处理该行.
关于c - 用C写一个程序把字符串分成token并打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18768838/