3

Hi I am having problems with sscanf. I am just trying to write a simple test program to help me understand how it works. The problem arises when writing to differents variables with sscanf. Here is what their values should be:

IP=175.85.10.147

number=2589

email = [email protected]

 #include <stdio.h> #include <stdlib.h> int main() { char *toSend = "175.85.10.147:2589:[email protected]"; int *number; char IP[200]; char email[300]; sscanf(toSend, "%[^:]: %i%[^:]: ", IP, number, email); printf("%s", IP); printf("%i", number); printf("%s", email); return 0; } 

The IP it prints correct.

The number doesn't print correctly, which might be related to this warning I'm getting at compile time: format '%i' expects argument of type 'int' but argument 2 has type 'int *'.

The email variable just contains bizarre characters for some reason.

6
  • You passed a pointer to an int as an argument to a function that takes an int in that position. remove the * from the variable declaration so that it reads int number; and see if that works. Commented Jan 18, 2017 at 23:20
  • Well, let's deal with the warning first. %i expects an int and you're giving it number which is int*. Commented Jan 18, 2017 at 23:20
  • 2
    int *number; --> int number;, sscanf(toSend,"%199[^:]: %i:%299s", IP, &number, email); Commented Jan 18, 2017 at 23:21
  • 2
    0100 means sixty-four, right? if you disagree use %d instead if %i Commented Jan 18, 2017 at 23:46
  • @Jasen: you are right, %i will magically parse 0 prefixed numbers as octal. Commented Jan 18, 2017 at 23:48

1 Answer 1

4

You need some memory to store number

i.e. change

int *number; 

to

int number; 

Then use

 sscanf(toSend,"%[^:]:%i:%[^:]",IP, &number, email); 

I have also correct the typos - here is the code http://ideone.com/hpqGDZ

#include <stdio.h> #include <stdlib.h> #include <assert.h> int main(){ char *toSend = "175.85.10.147:2589:[email protected]"; int number; char IP[200]; char email[300]; if (sscanf(toSend, "%199[^:]:%i:%299[^:]", IP, &number, email) != 3) { return 1; } printf("%s\n", IP); printf("%i\n", number); printf("%s\n", email); return 0; } 
Sign up to request clarification or add additional context in comments.

5 Comments

I don't think passing a reference to number is correct, that'll still have the type int* won't it?
@ArnauVanBoschkenArnauB - Please use BLUEPIXY sscanf with the enhancement that avoid buffer overruns
Yes - Was thinking that myself. - Updated the answer. Not sure if assert is the best way to go - but it will do
assert should only be used for debug runs. It's designed to compile to nothing on release builds. So N = scanf(...) assert(N ==3) is fine, but not to wrap the call.
Space before %i is redundant. There's absolutely no reason for it to be there.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.