c - 用C写一个程序把字符串分成token并打印出来

标签 c string

#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/

相关文章:

c - 基于队列数组的实现

c - Delphi/Pascal 字符串文字到 C/C++

string - 计算给定字符串 Haskell 中 Char 的实例数

python - 如何以编程方式对 python 字符串进行切片?

c - 在不同的头文件中定义 ARGS 有什么用?

c - 协助基本位操作

c - libPAPI : Maximum simultaneous events measure

c - ld: cannot perform PE operations on non PE output file 错误

c# - StringBuilder 和 string.IsIntern 方法

c - 请告诉我我做错了什么,因为 Monthstr2num 返回的值是错误的