【问题标题】:Parsing an array of chars for strings without for-loops?在没有for循环的情况下解析字符串的字符数组?
【发布时间】:2018-03-21 04:34:01
【问题描述】:

我有一个程序,它接受用户输入,范围可以是 5 个字符的命令,如“帮助”,也支持标志类型的命令,如“delete -p 'George'”

我对c++没有太多经验,除了做了一堆for循环,想知道是否有更有效的方法来解析char数组。

有人能指出正确的方向吗?

【问题讨论】:

  • 听起来你想解析命令行选项,看看boost::program_options
  • 您要求的是“更有效的方法”。比什么更有效,您目前的解决方案是什么?

标签: c++ arrays string parsing char


【解决方案1】:

除了注释中建议的 boost 库之外,如果您要解析一组相对较小的参数,您可以使用简单的 std::cin 在程序运行时接收参数,例如:

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> args;
    std::string arg;
    while(std::cin >> arg) {
        args.push_back(arg);
    }
}

上面需要一个EOF(不是回车)来标记命令的结束。

要使用回车来标记命令的结束,您需要getline(),如下所示:

std::vector<std::string> get_args() {
    using std::string;
    using std::stringstream; // don't forget to include <sstream> header

    string line;
    getline(std::cin, line);
    stringstream ss;
    ss << line;

    std::vector<string> cmds;
    string cmd;
    while (ss >> cmd) {
        cmds.push_back(cmd);
    }

    return cmds;
}

或者如果你想让你的主函数接受参数:

 int main(int argc, char **argv) {
     // The call to the excutable itself will be the 0th element of this vector
     std::vector<std::string> args(argv, argv + argc);
 }

【讨论】:

    【解决方案2】:

    是的,您可以像这样将 char 数组分配给字符串:

    char array[5] = "test";
    string str (array);
    cout << str;
    

    输出:

    test
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2023-03-10
      相关资源
      最近更新 更多