使用 istreamstream 模拟 sscanf's %*s
可能的重复:
sscanf() 的 C++ 替代方案
我有以下代码
sscanf(s, "%*s%d", &d);
行我如何使用 <代码> istringstream ?
我尝试了这个:
istringstream stream(s);
(stream >> d);
但由于 sscanf()
中的 *s
,它不正确。
Possible Duplicate:
C++ alternative to sscanf()
I have the following line of code
sscanf(s, "%*s%d", &d);
How would I do this using istringstream
?
I tried this:
istringstream stream(s);
(stream >> d);
But it is not correct because of *s
in sscanf()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与
sscanf
一起使用的%*s
基本上意味着忽略一个字符串(直到空格的任何字符),然后您就可以告诉它读取一个整数(%*s
%d
)。在这种情况下,星号 (*
) 与指针无关。因此,使用 stringstream,只需模拟相同的行为即可;读入一个字符串,在读入整数之前可以忽略该字符串。
IE。使用以下小程序:
输出将是:
d 的值为:123,我们忽略了:abc
。The
%*s
used withsscanf
basically means to ignore a string (any characters up until a whitespace), and then after that you're telling it to read in an integer (%*s
%d
). The asterisk (*
) has nothing to do with pointers in this case.So using
stringstream
s, just emulate the same behaviour; read in a string that you can ignore before you read in the integer.ie. With the following small program:
the output will be:
The value of d is: 123, and we ignored: abc
.您的代码中没有指针操作。
正如 AusCBloke 所说,您需要先读取所有不需要的字符将
int
转换为std::string
。您还希望确保处理s
的格式错误的值,例如具有任何整数的值。There is no pointer manipulation in your code.
As AusCBloke has said, you need to read the all of the unwanted characters before the
int
into astd::string
. You also want to ensure that you handle malformed values ofs
, such as those with any integers.