0

Possible Duplicate:
C++ alternative to sscanf()

I have the following line of code

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

How would I do this using istringstream?

I tried this:

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

But it is not correct because of *s in sscanf().

Community
  • 1
  • 1
user975900
  • 77
  • 4
  • 11
  • 4
    Please share your definitions of `s` and `d`. I am sure "the compiler's understanding" is just fine. – johnsyweb Oct 29 '11 at 00:59
  • 2
    @Johnsyweb Oh no! AI Compilers! Whatever you do, do **not** use an AI compiler to compile the source for the US nuclear missile launch program! And do not create any program called `Airnet.cpp` or `Skyweb.cpp`, either. – Mateen Ulhaq Oct 29 '11 at 01:45

2 Answers2

2

The %*s used with sscanf basically means to ignore a string (any characters up until a whitespace), and then after that you're telling it to read in an integer (%*s%d). The asterisk (*) has nothing to do with pointers in this case.

So using stringstreams, just emulate the same behaviour; read in a string that you can ignore before you read in the integer.

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

stream >> dummy >> d;

ie. With the following small program:

#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 output will be: The value of d is: 123, and we ignored: abc.

AusCBloke
  • 18,014
  • 6
  • 40
  • 44
1

There is no pointer manipulation in your code.

As AusCBloke has said, you need to read the all of the unwanted characters before the int into a std::string. You also want to ensure that you handle malformed values of s, such as those with any integers.

#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");
    }
}
Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247