【问题标题】:strtok() c++ How do I split a string with strtok() and put each part in a vector? [duplicate]strtok() c++ 如何用 strtok() 拆分字符串并将每个部分放入向量中? [复制]
【发布时间】:2015-01-19 03:29:25
【问题描述】:

我正在尝试实现一个基本终端(如 bash),我目前正在尝试接收用户输入(就像他们在 bash 中输入命令一样)并用空格分隔每个终端并将其放入向量中所以我可以从向量中读取并一一处理每个命令。 我似乎无法编译我的代码,我做错了什么? (这是我到目前为止所拥有的):

#include <iostream>
#include <cstring>
#include <vector>
#include <string>
using namespace std;

int main(){
    vector<string> cmdline;
    string command = "";
    cout << '$';
    getline(cin, command);

    command.c_str();
    char* tokchar;
    tokchar = strtok(command, " ");


    while(tokchar){
        cmdline.push_back(tokchar);
        tokchar = strtok(NULL, " ");
    }
 return 0;
 }

具体来说,编译器错误是:cannot convert 'std::string' to 'char*'for argument 1 to 'char* strtok(c​​har*, const char*)' 它说错误出现在我设置 tokchar =...;

我不确定这段代码是否能如我所愿。我将如何修复它并使其将所有命令行参数放入由“”分隔的向量中?

【问题讨论】:

    标签: c++ terminal strtok


    【解决方案1】:

    您正在使用 C++ 类型和一个对 C 来说更惯用的函数。请考虑将 boost::split 用于 C++。

    全部:

    char* tokchar;
    tokchar = strtok(command, " ");
    
    
    while(tokchar){
        cmdline.push_back(tokchar);
        tokchar = strtok(NULL, " ");
    }
    

    可以替换为(没有错误):

    boost::split( cmdline, command, boost::is_any_of(" ") );
    

    【讨论】:

    • 我的编译器说“boost is not declared”,我必须用 c++ 11 行编译吗?
    • @TristanZickovich C++03 或更高版本可以使用。您可以在提供的链接中阅读更多内容,但 #include &lt;boost/algorithm/string/split.hpp&gt; 将是一个开始。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    相关资源
    最近更新 更多