dor*_*ien 2 c++ string parsing casting
我有一个包含的c_str [51,53].我想将这些对分成两个整数.它们位于c_str中,因为我从输入文件中读取它们.
必须有一种简单的方法来解析它们.我在考虑使用这个.at功能:但我相信我已经成功了.此外,它不起作用,因为它输出:
pair: 0x7ffffcfc2998
pair: 0x7ffffcfc2998
etc
Run Code Online (Sandbox Code Playgroud)
string pairstring = buffertm.c_str();
stringstream pair1, pair2;
int pairint1, pairint2;
pair1 << pairstring.at(1) << pairstring.at(2);
cout << "pair: " << pair1;
pair1 >> pairint1;
pair2 << pairstring.at(4) << pairstring.at(5);
//cout << "pair: " << pair2;
pair2 >> pairint2;
Run Code Online (Sandbox Code Playgroud)
有更好的方法吗?
像这样的东西:
char c1, c2, c3;
int first, second;
std::istringstream iss(str);
if (iss >> c1 >> first >> c2 >> second >> c3
&& c1 == '[' && c2 == ',' && c3 == ']' )
{
// success
}
Run Code Online (Sandbox Code Playgroud)
您可能需要进行额外的检查以查看结束括号后是否还有更多字符:
if ((iss >> std::ws).peek() != EOF) {
//^^^^^^^^^^^^^^
// eats whitespace chars and returns reference to iss
/* there are redundant charactes */
}
Run Code Online (Sandbox Code Playgroud)