使用 istreamstream 模拟 sscanf 的 %*s

Emulating sscanf's %*s with istreamstream

本文关键字:sscanf istreamstream 模拟 使用      更新时间:2023-10-16

可能重复:
sscan((的C++替代方案

我有以下代码行

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

我该如何使用istringstream

我试过这个:

istringstream stream(s);
(stream >> d);

但由于CCD_ 3中存在CCD_。

%*ssscanf一起使用,基本上意味着忽略字符串(直到空白的任何字符(,然后告诉它读入一个整数(%*s%d(。在这种情况下,星号(*(与指针无关。

因此,使用stringstreams,只需模拟相同的行为;在读入整数之前,先读入一个可以忽略的字符串。

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");
    }
}