因此,对于我的问题,如果有人输入内容,我会解析它并将其存储到字符数组中。我按空间分隔用户类型。然后我将这些标记存储到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;
}
答案 0 :(得分:1)
您的代码中存在一些问题:
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;
}
答案 1 :(得分:0)
i
befote,否则您将调用未定义的行为。strlen(*argv)
不会提供令牌数量。你必须保存这个号码。scanf()
会为您解析,因此您不需要strtok()
更正后的代码:
#include <stdio.h>
#define MAXLINE 80
int main(void){
char * args[MAXLINE/2 + 1];
char buf [MAXLINE/2 + 1];
int i = 0, num;
char *token;
token = buf;
while(scanf("%s", token) == 1){
args[i++] = token;
token += strlen(token) + 1;
}
num = i;
//to print the array
for(i = 0; i < num;i++){
printf("%s\n", args[i]);
}
return 0;
}