gpt4 book ai didi

c - 在 C 程序中解析和存储 token

转载 作者:太空宇宙 更新时间:2023-11-04 03:31:58 27 4
gpt4 key购买 nike

所以对于我的问题,如果有人输入了一些东西,我会解析它并将它存储到一个字符数组中。我用空格分隔用户输入的任何内容。然后我将这些标记存储到 char 数组中并打印出来。但出于某种原因,在打印第一个单词后,打印出了一些乱码。这是我的代码:

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

#define MAXLINE 80

int main(void) {
char *args[MAXLINE / 2 + 1];
char buf[MAXLINE / 2 + 1];
scanf("%s", buf);
int i;
char *token;
token = strtok(buf, " ");
while (token != NULL) {
args[i++] = token;
token = strtok(NULL, " ");
}

//to print the array
for (i = 0; i < strlen(*args); i++) {
printf("%s\n" args[i]);
}
return 0;
}

最佳答案

您的代码中存在几个问题:

  • char buf[MAXLINE / 2 + 1];似乎不正确,缓冲区大小应为 MAXLINE+1 .
  • 你用scanf("%s", buf)读取了一个字符串: 这样的字符串将不包含任何空格字符。尝试用 strtok 解析它将始终生成单个标记,但在文件末尾除外,您不对其进行测试。你应该使用 fgets()相反。
  • i未初始化,存储指向 args[i++] 的指针调用未定义的行为。 i应初始化为 0 .
  • 最后的循环条件不正确:i < strlen(*args)没有意义,您应该使用与 0 不同的索引和循环至 i .

这是更正后的版本:

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

#define MAXLINE 80

int main(void) {
char *args[MAXLINE / 2];
char buf[MAXLINE + 1];

while (fgets(buf, sizeof buf, stdin)) {
int i = 0, j;
char *token = strtok(buf, " \t\n");
while (token != NULL) {
args[i++] = token;
token = strtok(NULL, " \t\n");
}
//to print the array
for (j = 0; j < i; j++) {
printf("%s\n" args[j]);
}
}
return 0;
}

关于c - 在 C 程序中解析和存储 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35689237/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com