【问题标题】:Storing a string token into an array将字符串标记存储到数组中
【发布时间】:2013-08-01 15:02:42
【问题描述】:

我正在使用 C++ 使用分隔符对字符串进行标记,并且可以在 while 循环中使用 cout 输出当前标记。我想做的是将令牌的当前值存储在一个数组中,以便我以后可以访问它。这是我现在拥有的代码:

string s = "Test>=Test>=Test";
string delimiter = ">=";
vector<string> Log;
int Count = 0;
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != string::npos) {
token = s.substr(0, pos);
strcpy(Log[Count].c_str(), token.c_str());
Count++;

s.erase(0, pos + delimiter.length());
}

【问题讨论】:

  • 这肯定不会编译。您如何将strcpy() 转换为c_str() 调用的结果?您应该简单地将push_back() 令牌放入日志中。

标签: c++ arrays token


【解决方案1】:

只需在矢量上使用push_back。它会为您将令牌复制到向量中。无需数数;不需要strcpy:

string s = "Test>=Test>=Test";
string delimiter = ">=";
vector<string> Log;
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != string::npos) {
    token = s.substr(0, pos);
    Log.push_back(token);
    s.erase(0, pos + delimiter.length());
}

【讨论】:

    【解决方案2】:

    push_back() 会做你需要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-23
      • 2015-02-08
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-20
      • 1970-01-01
      相关资源
      最近更新 更多