我有一个字符串数组cmd,其容量为255个字符:
char cmd[255];
我使用fgets以这种方式获取用户输入:
fgets(cmd, 256, stdin);
我有三个独立的数组来存储三个令牌(假设用户只输入一个最多2个空格的字符串)这样声明:
char arg[20];
char arg2[20];
char arg3[20];
我用这样的方式将字符串拆分为cmd:
char *p = strtok(cmd, " ");
while (p!= NULL) {
// I want to store the tokens p in the arrays here (e.g:
// arg = p is not working
// arg2 = p ...
p = strtok(NULL, " ");
}
以这种方式指定指针中的值不起作用。我可以得到一些帮助吗?
我必须将标记存储在空终止字符串
中答案 0 :(得分:1)
#include <stdio.h>
#include <string.h>
#define ARG_LEN 20
int main(void){
char cmd[256];
if(fgets(cmd, sizeof cmd, stdin)){
char arg[ARG_LEN+1], arg2[ARG_LEN+1], arg3[ARG_LEN+1];
char *args[] = { arg, arg2, arg3, NULL };
char **pp = args;
const char *delimiter = " \t\n";//Include \n
for(char *p = strtok(cmd, delimiter); p && *pp; p = strtok(NULL, delimiter)){
strncpy(*pp, p, ARG_LEN);
(*pp++)[ARG_LEN] = 0;//Cut it if it is too long
}
for(size_t i = 0; args + i < pp; ++i){
printf("argument #%zu: '%s'\n", i+1, args[i]);
}
}
}
sscanf版本。
#include <stdio.h>
//Stringification
#define S_(n) #n
#define S(n) S_(n)
#define FMT "%" S(ARG_LEN) "s"
#define ARG_LEN 20
int main(void){
char cmd[256];
if(fgets(cmd, sizeof cmd, stdin)){
char arg[ARG_LEN+1], arg2[ARG_LEN+1], arg3[ARG_LEN+1];
char *args[] = { arg, arg2, arg3 };
int ret_scnf = sscanf(cmd, FMT FMT FMT, arg, arg2, arg3);
for(int i = 0; i < ret_scnf; ++i){
printf("argument #%i: '%s'\n", i+1, args[i]);
}
}
}
答案 1 :(得分:0)
以下可能有效。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
char cmd[255] = "";
char arg[20] = "" ;
char arg2[20] = "";
char arg3[20] = "";
char *p;
fgets(cmd, 255, stdin );
p = strtok(cmd, " ");
if ( p != NULL ) {
strcpy( arg, p );
p = strtok(NULL, " ");
if ( p != NULL ) {
strcpy( arg2, p );
p = strtok(NULL, "");
if ( p != NULL ) {
strcpy( arg3, p );
}
}
}
printf(" arg=%s\n arg2=%s\n arg3=%s\n", arg, arg2, arg3);
return 0;
}
答案 2 :(得分:0)
建议:声明argv如下
char argv[3][20];
通过这样做,它将简化如下代码:
int
main(void)
{
char cmd[255];
char argv[3][20];
char *token;
char *tstr = " ";
fgets( cmd, sizeof cmd, stdin );
token = strtok( cmd, tstr );
int i = 0;
while( token != NULL )
{
strcpy( argv[i], token);
printf( "%s\n", argv[i] );
token = strtok( NULL, tstr );
i++;
}
return 0;
}