+ 1

Why did this code do not make error, if input would be Smith like "4.5"? How to solve the problem

https://code.sololearn.com/c74YEq2GN8QZ/?ref=app

9th Jun 2022, 6:43 AM
Егор Копоть
Егор Копоть - avatar
5 Respostas
+ 1
%d stands for decimal and it expects an argument of type int. Floating-point types float and double both of them use %f. In C99 you can also use %lf to signify the larger size of double. float a; scanf("%f", &a); printf("Hello, %.1f\n", a);
9th Jun 2022, 8:11 AM
SoloProg
SoloProg - avatar
+ 1
I mean, the program should work with integer only, and if user would input float — it needs to return error.
9th Jun 2022, 8:21 AM
Егор Копоть
Егор Копоть - avatar
+ 1
Here is a way to do it with all integers: #include <stdio.h> int main() { int a, b=-1; scanf("%d.%d", &a, &b); if (b>=0) puts("Invalid input"); else printf("Hello, %d\n", a); return 0; } Use scanf to detect the decimal point and place the decimal portion into b. If b is changed from its initialized value of -1 then you can tell that it was floating point input.
9th Jun 2022, 5:42 PM
Brian
Brian - avatar
+ 1
// Hope this code helps you https://code.sololearn.com/c6hJ3kE5mMxN char sn[10]; fgets (sn, sizeof(sn), stdin); int na=0; for (int i=0; i<strlen(sn); i++) { if ( !isdigit(sn[i]) ) { na++; break; } } if (na>0) puts("Invalid Input, n should be integer number"); else printf("%d", atoi(sn) );
9th Jun 2022, 5:49 PM
SoloProg
SoloProg - avatar
0
Thanks. :) We have a task to use only 'stdio' library, and have a deadline with one day only. So finally we got something like that (but I do not understand, why it always give me invalid output there). https://code.sololearn.com/ch5utWF8ULP5/?ref=app
12th Jun 2022, 1:05 PM
Егор Копоть
Егор Копоть - avatar