strtok 不打印字符串的所有部分
strtok not printing all parts of string
我正在尝试获取输入字符串中的所有标记
#include <stdio.h>
#include <unistd.h>
#define MAX_LINE 80
int main(void)
{
char *args[MAX_LINE/2+1];
char *tokens[MAX_LINE/2+1];
int should_run = 1;
char *split;
int i = 0;
int concurrent = 0;
printf("osh>");
fflush(stdout);
scanf("%s", args);
split = strtok(args," ");
while(split!=NULL)
{
printf(split);
tokens[i]=strdup(split);
split = strtok(NULL, " ");
i++;
}
}
为什么上面的代码没有打印出我的字符串中的所有标记
例如,如果我的输入是 "ls -l &" 它只打印 ls?
感谢您的宝贵时间
问题出在第 scanf("%s", args);
行。它读取字符串直到空格。您可以改为使用 scanf("%[^\n]", args);
。并将 char* args[MAX_LINE/2+1];
更改为 char args[MAX_LINE/2+1];
*split需要指向一块内存,
或者:
1) 一个足够大的数组,拆分指向数组[0]。
2) 在块开始附近使用 malloc,在块结束附近使用 free(split);。
这两种模式可以互换,不要混用,会造成很大的问题。
我正在尝试获取输入字符串中的所有标记
#include <stdio.h>
#include <unistd.h>
#define MAX_LINE 80
int main(void)
{
char *args[MAX_LINE/2+1];
char *tokens[MAX_LINE/2+1];
int should_run = 1;
char *split;
int i = 0;
int concurrent = 0;
printf("osh>");
fflush(stdout);
scanf("%s", args);
split = strtok(args," ");
while(split!=NULL)
{
printf(split);
tokens[i]=strdup(split);
split = strtok(NULL, " ");
i++;
}
}
为什么上面的代码没有打印出我的字符串中的所有标记 例如,如果我的输入是 "ls -l &" 它只打印 ls?
感谢您的宝贵时间
问题出在第 scanf("%s", args);
行。它读取字符串直到空格。您可以改为使用 scanf("%[^\n]", args);
。并将 char* args[MAX_LINE/2+1];
更改为 char args[MAX_LINE/2+1];
*split需要指向一块内存, 或者:
1) 一个足够大的数组,拆分指向数组[0]。
2) 在块开始附近使用 malloc,在块结束附近使用 free(split);。
这两种模式可以互换,不要混用,会造成很大的问题。