0

可能重复:
C++ 替代 sscanf()

我有以下代码行

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

我将如何使用istringstream

我试过这个:

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

但它不正确,因为*sin sscanf()

4

2 回答 2

2

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

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

int d;
string dummy;
istringstream stream(s);

stream >> dummy >> d;

IE。使用以下小程序:

#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;
}

输出将是:The value of d is: 123, and we ignored: abc

于 2011-10-29T01:11:18.627 回答
1

您的代码中没有指针操作。

正如AusCBloke所说,您需要intstd::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");
    }
}
于 2011-10-29T01:32:43.227 回答