Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在argc和argv中分配字符串_C_Linux - Fatal编程技术网

如何在argc和argv中分配字符串

如何在argc和argv中分配字符串,c,linux,C,Linux,我正在编写一个用户验证程序,成功登录后,我提供了一个类似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");

我正在编写一个用户验证程序,成功登录后,我提供了一个类似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库可以做到这一点,或者是否有任何最佳实践提示或示例可以继续

最后,我必须解析argc和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]=./demoargv[1]=用户名(abhijatya)argv[2]=密码(1234)。


请展示您的研究成果。请先阅读第页。
argc
argv
是运行程序时操作系统填写的
main
函数的参数。在您的代码中,它们是未初始化的局部变量。您希望他们如何保存合理的数据?仅将它们命名为
argc
argv
并不能让它们神奇地引用命令行参数。请注意,
main
的原型是
intmain(intargc,char**argv)。在你的问题中,你说的是
int**argv