C ++如何将其拆分为矢量并使用它

Possible Duplicate:
Splitting a string in C++




我正在使用C ++进行客户端服务器编程。

我的客户发送带有值的字符串

string receiveClient = "auth#user:pass";


如何用receiveClient'#'作为分隔符分割':'变量?



我尝试使用在线找到的此功能

vector split (const string &s,char delim)
{
  vector string elems;
  return(s,delim,elems);
}


我在main()上做到了:

vector x = split(&receiveClient,"#");


但它给我以下

server.cpp: In function ‘int main()’:
server.cpp:128:8: error: missing template arguments before ‘x’
server.cpp:128:8: error: expected ‘;’ before ‘x’
root@ubuntu:/home/baoky/csci222_assn2# g++ server server.cpp
server.cpp:47:1: error: invalid use of template-name ‘std::vector’ without an argument list
server.cpp: In function ‘int main()’:
server.cpp:128:8: error: missing template arguments before ‘x’
server.cpp:128:8: error: expected ‘;’ before ‘x’


感谢所有帮助。不胜感激


最佳答案:

通常,使用C ++中的流最容易完成此类任务。这样的事情应该起作用:

// Beware, brain-compiled code ahead!

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

std::vector<string> splitClientAuth(const std::string& receiveClient)
{
  // "auth#user:pass"
  std::istringstream iss(receiveClient);

  std::vector<std::string> strings;
  strings.resize(3);
  std::getline(iss, strings[0], '#');
  std::getline(iss, strings[1], ':');
  std::getline(iss, strings[2]); // default is '\n'

  if( !iss && !iss.eof() )
    throw "Dude, you badly need an error handling strategy!";

  if( string[0].empty() || string[1].empty() || string[2].empty() )
    throw "Watcha gonna do now?";

  return strings;
}




还有几点值得注意的地方:


这些真的是纯文本密码吗?
std::vector<std::string>中使用它对我来说似乎是可疑的。如果那是我的代码,我希望有一个数据结构来存储用户信息,并将发现的内容写进去。
从您的判断完全无法理解您在问题中粘贴的代码(Martinho是正确的,那太糟糕了,是否仍然可以将其视为C ++是有争议的),并且从您的评论来看,您似乎急需。