c++ - 在没有 for 循环的情况下解析字符串的字符数组?

标签 c++ arrays string parsing char

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

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

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

最佳答案

除了评论中建议的 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);
 }

关于c++ - 在没有 for 循环的情况下解析字符串的字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46655379/

相关文章:

python - 如何使用 cffi 在 C 语言中嵌入返回字符串的 Python 函数?

c++ - 如何使用 RapidXML C++ 检查 xml 中的空标记

arrays - 傀儡排序是如何工作的?

c - 映射枚举和字符串

python - 按所有零行对 2D NumPy 数组进行切片

python - 如何使用 kd-trees 确定字符串相似性?

c - 将带有空格的字符串拆分为 C 中的字符串 vector

c++ - 如何引入标准库的意外构建依赖项

c++ - 引用指向 int 的指针会导致错误

c++ - 佳能SDK。从相机拍照