The user has to write a number in the programm. Is there something else I can use for a number input instead of scanf?
Asked
Active
Viewed 47 times
0
-
4Use `fgets` and then `strtol` for `int` and `strtod` for `double`. – Jabberwocky Nov 09 '22 at 16:23
-
Do you get problems when you use `scanf`? – Sergey Kalinichenko Nov 09 '22 at 16:25
-
3Avoid `scanf()` for _all_ input. Use `fgets()`. – chux - Reinstate Monica Nov 09 '22 at 16:27
-
Hint: google _avoid scanf_ – Jabberwocky Nov 09 '22 at 16:29
-
1Please explain the reasons for avoiding scanf. That is needed to recommend an alternative and for verifying that we are not looking at a [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Yunnosch Nov 09 '22 at 16:37
-
2Reasons to avoid scanf: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html – William Pursell Nov 09 '22 at 16:41
-
1Stop thinking of it as "user input". It is input. Whether it comes from a human or a socket or a file or anything else is (mostly) irrelevant. – William Pursell Nov 09 '22 at 16:43
-
You have multiple options, depending on the standard functions you like to use. Did you look through the usual documentation? Why does it not help you? – the busybee Nov 09 '22 at 17:56
-
For user _interactive_ input with a prompt (e.g. `printf("Enter a number: "); fflush(stdout); int num; scanf("&d",&num);`), I recommend `fgets` followed by `strtol`. See my answer: [Check if all values entered into char array are numerical](https://stackoverflow.com/a/65013419/5382650) – Craig Estey Nov 09 '22 at 18:15
-
user378246, what should happen if input is not in the number's range or is non-numeric? It is that question that drives the best way to handle input. – chux - Reinstate Monica Nov 09 '22 at 22:40
-
You may want to take a look at my function `get_int_from_user` from [this answer of mine to another question](https://stackoverflow.com/a/73915292/12149471). That function will automatically reprompt the user for input if the input is invalid, for example if the user does not enter a number. – Andreas Wenzel Jul 24 '23 at 18:58