多个分隔符

时间:2012-11-14 14:35:05

标签: c++ delimiter

我有来自具有多个分隔符的文件的输入,例如

years,(7),(9)
years,(8),(3)

我可以用什么方法将它们分开为

years
7
9
years
8
3

我试图使用strok但是我没有显示以下内容。

getline (myfile,line, ',' );
line = strtok (pch," (),");

我从http://www.cplusplus.com/reference/clibrary/cstring/strtok/

得到了这个例子

2 个答案:

答案 0 :(得分:2)

这看起来像是std::locale的工作和他值得信赖的伙伴imbue

#include <locale>
#include <iostream>


struct punct_ctype : std::ctype<char> {
  punct_ctype() : std::ctype<char>(get_table()) {}
  static mask const* get_table()
  {
    static mask rc[table_size];
    rc[' '] = std::ctype_base::space;
    rc['\n'] = std::ctype_base::space;
    rc['('] = std::ctype_base::space;
    rc[')'] = std::ctype_base::space;
    rc[','] = std::ctype_base::space;
    return &rc[0];
  }
};

int main() {
  using std::string;
  using std::cin;
  using std::locale;

  cin.imbue(locale(cin.getloc(), new punct_ctype));

  string word;
  while(cin >> word) {
    std::cout << word << "\n";
  }
}

答案 1 :(得分:0)

你没有使用strtok权利:

char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
  printf ("%s\n",pch);
  pch = strtok (NULL, " ,.-");
}

有关详细信息,请参阅http://www.cplusplus.com/reference/clibrary/cstring/strtok/