Possible Duplicate:
C++ alternative to sscanf()
我有以下代码行
sscanf(s, "%*s%d", &d);
我将如何使用
istringstream
执行此操作?我尝试了这个:
istringstream stream(s);
(stream >> d);
但这是不正确的,因为
*s
中的sscanf()
。 最佳答案
与%*s
一起使用的sscanf
基本上意味着忽略字符串(直到空白的所有字符),然后,您告诉它读取整数(%*s
%d
)。在这种情况下,星号(*
)与指针无关。
因此,使用stringstream
只需模拟相同的行为即可。读入一个在整数之前可以忽略的字符串。
int d;
string dummy;
istringstream stream(s);
stream >> dummy >> d;
即。使用以下小程序:
#include <iostream>
#include <sstream>
using namespace std;
int main(void)
{
string s = "abc 123";
int d;
string dummy;
istringstream stream(s);
stream >> dummy >> d;
cout << "The value of d is: " << d << ", and we ignored: " << dummy << endl;
return 0;
}
输出将是:
The value of d is: 123, and we ignored: abc
。关于c++ - 用istreamstream模拟sscanf的%* s ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7936274/