我正在编写一个用户验证程序,成功登录后我提供了一个类似 shell 的提示:
int main()
{
int argc;
char **argv;
char *username = malloc(50);
char *passwd = malloc(32);
char command[200];
printf("Enter username:");
scanf("%s", username);
printf("\n");
printf("Enter password:");
get_passwd(passwd); //User defined function for taking the password without echoing.
// Then a authentication module is called;
int success = authenticate_user(username, passwd);
//After successful authentication of user I will print like:
printf("test @ %s >", username);
// To look user that he is working on program's own terminal where user can input some command as string
gets(command);
//Here is the main problem
// I tried using strtok() and g_shell_parse_argv () but not getting the desired result.
return 0;
}
其他团队成员根据命令字符串解析编写了进一步操作的程序。他们表示我必须了解如何将其解析为 argc 和 argv 变量,就像 main(int argc, int **argv) 函数签名形式变量中一样。
是否有任何 C 库可以做到这一点,或者有任何最佳实践提示或示例可以继续。
Finally I have to parse a string in argc and argv.
非常感谢任何帮助。 谢谢。
最佳答案
对于命令行参数,您必须使用它,
int main(int argc, char **argv)
在您的代码中,您可以这样做。
int main(int argc, char **argv) { //your remaining code int success = authenticate_user(argv[1], argv[2]); }
例如,当您运行像这样的程序时,
./demo username password (./demo abhijatya 1234)
因此, argv[0] = ./demo 、 argv[1] = 用户名(abhijatya ) 和 argv[2] = 密码(1234).
关于c - 如何在 argc 和 argv 中分配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35152305/