2

I need to convert this line to use cin.

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

What's the difference between sscanf and scanf and cin?

Fred Nurk
  • 13,952
  • 4
  • 37
  • 63
  • 5
    Check your C documentation for the difference between sscanf and scanf. – Jim Balter Feb 11 '11 at 08:11
  • 2
    You won't be able to do this using `cout`; that's for output and `sscanf` is for input. You'll probably want to use `cin`. – templatetypedef Feb 11 '11 at 08:12
  • 2
    For any programming language its important to have sufficient good documentation. See: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list & http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list If you're on Unix or Linux the manual pages will be installed so 'man sscanf' man 'scanf' would help. – David Victor Feb 11 '11 at 08:33
  • 1
    @Kirill: Whatever this question's merits (or lack thereof), it's the exact opposite of that question, not a duplicate in the least. – Nicholas Knight Feb 11 '11 at 08:37
  • @Valentina I've edited your question to refer to `cin`. –  Feb 11 '11 at 08:40
  • 2
    To all who closed - this is not a duplicate of that question. It's totally different. – templatetypedef Feb 11 '11 at 08:41
  • @Valentina & Ninefinger edited title to match question – jk. Feb 11 '11 at 10:22

1 Answers1

5

You can't for two reasons. First, cout is for output and the scanf family is for input, but also sscanf parses a string, so the iostream equivalent would be an istringstream.

Secondly, the format string can't be matched. The first directive (%*s) reads non-whitespace characters (as a string because of the S) and then discards them (because of the asterisk). The second directive reads an int, but any integer that would have been present at this point would have already been read and discarded. After the first directive, you will either have no more input characters or the next character will be whitespace.

If, instead, you had:

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

Then you would read non-whitespace, some whitespace, and then an integer. The easiest stringstream equivalent to this would be:

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;
Fred Nurk
  • 13,952
  • 4
  • 37
  • 63