我需要将此行转换为使用cin.
sscanf(s, "%*s%d", &d);
Run Code Online (Sandbox Code Playgroud)
sscanf与scanf和cin有什么区别?
你不能出于两个原因.首先,cout用于输出,scanf系列用于输入,但sscanf也会解析字符串,因此iostream等价物将是一个istringstream.
其次,格式字符串不能匹配.第一个指令(%*s)读取非空白字符(因为S而作为字符串),然后丢弃它们(因为星号).第二个指令读取一个int,但此时已存在的任何整数都已被读取并丢弃.在第一个指令之后,您将不再有输入字符,或者下一个字符将是空格.
相反,如果你有:
sscanf(s, "%*s %d", &d)
Run Code Online (Sandbox Code Playgroud)
然后你会读取非空格,一些空格,然后是整数.与此相当的最简单的字符串流将是:
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;
Run Code Online (Sandbox Code Playgroud)