将optarg作为C ++字符串对象获取

时间:2009-03-06 00:52:08

标签: c++ string getopt getopt-long

我使用getopt_long来处理C ++应用程序中的命令行参数。这些示例在处理示例中都显示了类似printf("Username: %s\n", optarg)的内容。这非常适合显示示例,但我希望能够实际存储这些值以供以后使用。其余大部分代码都使用string个对象而不是char*,所以我需要将optarg的内容/任何内容转换/复制到字符串中。

string bar;
while(1) {
    c = getopt_long (argc, argv, "s:U:", long_options, &option_index);
    if (c == -1) break;
    switch(c)
        {
            case 'U':
                // What do I need to do here to get
                // the value of optarg into the string
                // object bar?
                bar.assign(optarg);
                break;
        }
}

上面的代码编译,但是当它执行时,如果我尝试使用printf打印出bar的值,则会出现Illegal instruction错误(对于cout来说它似乎工作得很好)。

// Runs just fine, although I'm not certain it is actually safe!
cout << " bar: " << bar << "\n";

// 'Illegal instruction'
printf(" bar: %s\n", bar);

我不太了解命令行调试,以便更好地了解非法指令可能是什么。我一直在运行valgrind,但是由于这个错误导致的大量内存错误使我很难确切地指出可能导致此错误的原因。

3 个答案:

答案 0 :(得分:7)

你告诉printf你在指定%s时提供了c样式字符串(空终止字符数组),但是你提供了一个字符串类。假设你正在使用std :: string试试:

printf("bar : %s\n", bar.c_str());

答案 1 :(得分:6)

printf()无法处理C ++ string。请改用bar.c_str()

答案 2 :(得分:3)

cout << " bar: " << bar << "\n";

非常安全。是什么让你觉得它可能不是?