按空格标记字符串

时间:2015-09-08 10:14:39

标签: c++

我有以下char*

char* config = "username 12345 google.com 225";

在尝试按空格分割时,我希望结果是字符串中包含的vector<string>个单词,但我只得到第一个单词,而不是更多。

以下是我使用的代码:

istringstream iss_str(config);
string token;
// storage for splitted config data
vector<string> tokens;

// port number is an integer value, hence it should
// be type-cast back to integer
int config_int_port = 0;

while( getline(iss_str, token, ' ') ) // I also have replaced space with \000 but to no avail
{
    tokens.push_back(token);
}

我得到的结果是一个大小为1的向量,它只包含第一个单词username

我也使用了以下方法,但结果与前一个相同:

copy(istream_iterator<string>(iss_str),
     istream_iterator<string>(),
     back_inserter(tokens));

更新 我使用以下函数来执行上面的代码:

void __cmd_conf(char* __config)

它被称为:

__cmd_conf(optarg);

optarg是linux的下一个选项参数的全局变量。

1 个答案:

答案 0 :(得分:1)

此代码对我有效:

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

using namespace std;

int main() {
  const char* config = "username 12345 google.com 225";
  istringstream iss_str(config);
  string token;
  // storage for splitted config data
  vector<string> tokens;

  // port number is an integer value, hence it should
  // be type-cast back to integer
  int config_int_port = 0;

  while( getline(iss_str, token, ' ') )
    {
      cout << "token " << token << "\n";
      tokens.push_back(token);
    }
  cout <<"tokens len "<<tokens.size()<<"\n";
}

输出是:

token username
token 12345
token google.com
token 225
tokens len 4