2

I am completely new to C and don't quite understand how the scanf function works. What I want it to do, is to take one string as the first input ('rgb'), and three more integers ('r, g, b'). This is the code:

    if(scanf(" %s ( %d , %d , %d )", rgb, &r, &g, &b) == 1){
    printf("Wrong input.\n");
    return 1;
};

If the user writes 'rgb ( 255 , 255 , 255 )' it works just fine. However, if they do not type spaces, it will not work. I want it to work in both cases, with or without spaces and definitely with commas and brackets.

Thanks in advance

  • 2
    Take the spaces out of the format string. – dbush Oct 17 '21 at 13:49
  • 4
    Aside: instead of `== 1` use `!= 4` – Weather Vane Oct 17 '21 at 13:49
  • 2
    Since you are requesting 4 inputs, `scanf` will return 4 if it succeeds. – Steve Summit Oct 17 '21 at 13:50
  • 2
    Your other problem is that since you are completely new to C, you cannot possibly understand how `scanf` works, since `scanf` is one of the most confusing, poorly designed, and ultimately useless functions in the entire C library. Yet `scanf` is only ever used in "beginning" C programs, since it has no use in "real" C programs at all. – Steve Summit Oct 17 '21 at 13:52
  • 1
    That is, `scanf` will return 4 if it successfully scans and stores a value for each of the four formatting directives. It is a bit fraught to call that "succeeds". In particular, if it does scan and store four fields then it will return 4 whether or not it also scans a trailing `)`. – John Bollinger Oct 17 '21 at 13:52
  • If you want to use `scanf` without problems, try to stick to the [rules listed here](https://stackoverflow.com/questions/69213541/coding-errors-in-c-programming/69223945#69223945). And when you're ready to abandon `scanf`, you can [read about some preferred alternatives](https://stackoverflow.com/questions/58403537). – Steve Summit Oct 17 '21 at 13:54
  • @JohnBollinger Good point. I'm mildly surprised more people don't ask, "How can I ensure `scanf` actually matched trailing explicit characters in the format string?" I suppose the answer would involve `%n`. – Steve Summit Oct 17 '21 at 13:57

0 Answers0