gpt4 book ai didi

c++ - 如何将 sscanf 的使用转换为 cin?

转载 作者:搜寻专家 更新时间:2023-10-31 00:46:36 24 4
gpt4 key购买 nike

我需要将此行转换为使用 cin。

sscanf(s, "%*s%d", &d);

sscanf与scanf和cin有什么区别?

最佳答案

你不能这样做有两个原因。首先,cout 用于输出,scanf 系列用于输入,而且 sscanf 还解析字符串,因此 iostream 等效项是 istringstream。

其次,格式字符串无法匹配。第一个指令 (%*s) 读取非空白字符(由于 S 而作为字符串)然后丢弃它们(由于星号)。第二条指令读取一个 int,但此时出现的任何整数都已被读取并丢弃。在第一个指令之后,您将没有更多的输入字符,或者下一个字符将为空白。

相反,如果您有:

sscanf(s, "%*s %d", &d)

然后您将读取非空白、一些空白,然后是一个整数。与此等效的最简单的字符串流是:

std::istringstream ss (s);  // Put the initial string s into the stream.
int d;
std::string _; // Used but then ignored; this is easier than alternatives.
ss >> _ >> d;

关于c++ - 如何将 sscanf 的使用转换为 cin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4966838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com