1

I have a file that contains data in this form:

1 Jake 234 Ruby 98.

I want to use sscanf to read only the strings into arrays, so I tried this:

male[i] = malloc(100);
female[i] = malloc(100);

sscanf(str, "%*d%s%*d%s%*d", &male[i], &female[i]);

The problem is that when i = 0, the function skips the first string along with the first integer. So when I try to print &male[0], I get a blank space.

I have initialised i to be 0. Could someone please point out where I might be going wrong?

Thanks a lot!

2
  • try this : sscanf(str, "%*d%s%*d%s%*d", male[i], female[i]); printf("%s %s\n", male[i], female[i]); Commented Apr 7, 2014 at 0:24
  • 1
    Why are you not testing the result of sscanf()? You must test the to know how much of it worked, which helps identify where the problem is. You'll never know whether the last %*d succeeded so it may as well be deleted. Commented Apr 7, 2014 at 2:32

1 Answer 1

3
  1. Use male[i] rather than &male[i].

  2. Limit your string input by 99 (1 less than the size of the buffer space)

  3. Check the return value of sscanf()

  4. The last "%*d" does not do anything.

-

char *male[N]; // assumed sample declaration
char *female[N];

male[i] = malloc(100);
female[i] = malloc(100);
int cnt = sscanf(str, "%*d%99s%*d%99s", male[i], female[i]);
if (cnt == 2) Success();

If you want to insure all the data is parsed and no non-white-space at the end....

int n = 0;
int cnt = sscanf(str, "%*d%99s%*d%99s%*d %n", male[i], female[i], &n);
if (cnt == 2 && str[n] == '\0') Success();
Sign up to request clarification or add additional context in comments.

1 Comment

@BLUEPIXY Thanks - caught that on 1 line but not 2 - now fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.