【问题标题】:how to assign a string in argc and argv [duplicate]如何在 argc 和 argv 中分配字符串 [重复]
【发布时间】:2016-05-11 04:32:43
【问题描述】:

我正在编写一个用户验证程序,成功登录后,我提供了一个类似 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 中解析一个字符串。

非常感谢任何帮助。 谢谢。

【问题讨论】:

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

标签: c linux


【解决方案1】:
  • 对于命令行参数,你必须使用这个,

    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] = username(abhijatya)argv[2] = 密码(1234)。

【讨论】:

    猜你喜欢
    • 2017-12-22
    • 2020-10-12
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 2014-10-09
    • 2011-10-20
    • 1970-01-01
    相关资源
    最近更新 更多