使用 istreamstream 模拟 sscanf 的 %*s
Emulating sscanf's %*s with istreamstream
可能重复:
sscan((的C++替代方案
我有以下代码行
sscanf(s, "%*s%d", &d);
我该如何使用istringstream
?
我试过这个:
istringstream stream(s);
(stream >> d);
但由于CCD_ 3中存在CCD_。
%*s
与sscanf
一起使用,基本上意味着忽略字符串(直到空白的任何字符(,然后告诉它读入一个整数(%*s
%d
(。在这种情况下,星号(*
(与指针无关。
因此,使用stringstream
s,只需模拟相同的行为;在读入整数之前,先读入一个可以忽略的字符串。
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;
}
输出为:CCD_ 10。
代码中没有指针操作。
正如AusCBloke所说,您需要将int
之前的所有不需要的字符读取为std::string
。您还需要确保处理格式不正确的s
值,例如具有任何整数的值。
#include <cassert>
#include <cstdio>
#include <sstream>
int main()
{
char s[] = "Answer: 42. Some other stuff.";
int d = 0;
sscanf(s, "%*s%d", &d);
assert(42 == d);
d = 0;
std::istringstream iss(s);
std::string dummy;
if (iss >> dummy >> d)
{
assert(dummy == "Answer:");
assert(42 == d);
}
else
{
assert(!"An error occurred and will be handled here");
}
}
相关文章:
- 用C++中的sscanf赋值
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 具有结构成员char数组的sscanf
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- sscanf() 有两个字符串参数
- SSCANF 进入 uint8 阵列失败
- Arduino使用sscanf读取浮点数
- 使用 sscanf 设置结构引用的值
- 如何使用 sscanf 提取浮点数?
- 使用 sprintf 和 sscanf 将给定数字中的所有 0 替换为 5
- SSCANF 无法读取双十六进制
- 切换到新编译器后,SSCANF 的工作方式有所不同
- sscanf 格式参数不起作用
- 具有十六进制值的SSCANF
- 扫描字符 [] 和 int 时 sscanf 中出现错误
- 用C 中的SSCANF解析消息
- C SSCANF实现问题(从文件中读取)
- sscanf(s、"%u" 和 v) 匹配有符号整数
- SSCANF读取1而不是3个浮点
- 使用 istreamstream 模拟 sscanf 的 %*s