C++ cin 与 C sscanf
所以我用 C 写了这个,所以 sscanf 扫描 s 但然后丢弃它,然后扫描 d 并存储它。因此,如果输入是“Hello 007”,则会扫描 Hello 但将其丢弃,并将 007 存储在 d 中。
static void cmd_test(const char *s)
{
int d = maxdepth;
sscanf(s, "%*s%d", &d);
}
所以,我的问题是如何在 C++ 中做同样的事情?可能使用字符串流?
So i wrote this in C, so sscanf scans in s but then discards it, then scans in d and stores it. So if the input is "Hello 007", Hello is scanned but discarded and 007 is stored in d.
static void cmd_test(const char *s)
{
int d = maxdepth;
sscanf(s, "%*s%d", &d);
}
So, my question is how can I do the same thing but in C++? possibly using stringstream?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法真正提取到匿名字符串,但您可以创建一个虚拟字符串并忽略它:
请注意,提取可能会失败,因此我输入了条件。发生错误时由您决定; C++ 要做的事情是抛出异常(尽管如果您的实际函数已经传达错误,您可能只能
返回
一个错误)。用法示例:
You can't really extract into an anonymous string, but you can just make a dummy and ignore it:
Note that the extraction might fail, whence the conditional I put in. It's up to you what you do in case of an error; the C++ thing to do would be to throw an exception (though if your actual function communicates errors already, you might be able to just
return
an error).Example usage:
怎么样:
What about: