Reputation: 1
I am trying to solve this HackerRank challenge:
There are 3 variables already declared: i(integer), d(double), and s(string).
I must declare 3 more variables of the same type as the previous, requesting input with scanf().
Then print sum of i with the second int variable. Then print the sum of d with the second double variable.
Finally, and the only task that I am not able to complete, is to concatenate the s string with the second char variable(string).
The first two tasks were completed smoothly, but the concatenation is not running.
I am getting as output only the first string and 0. (HackerRank 0.)
Here is the code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int i = 4;
double d = 4.0;
char s[] = "HackerRank ";
int secondI;
float secondD;
char s2[100];
scanf("%d", &secondI);
scanf("%1f", &secondD);
scanf("%s", s2);
printf("%d\n",i + secondI);
printf("%.1f\n", d + secondD);
printf("%s ", s);
printf("%s", s2);
return 0;
}
```
`
Expected Output
16
8.0
HackerRank is the best place to learn and practice coding!
My Output (stdout)
16
8.0
HackerRank .0
Upvotes: -3
Views: 74
Reputation: 108978
scanf("%1f", &fvar)
reads one character and interprets that single char as a float value which is written into the variable. The rest of the input is then used for the next scanf()
.
Use scanf("%f", &fvar)
with floats ... or scanf("%lf", &dvar)
with doubles.
And also check the return value of scanf
if (scanf("%lf", &dvar) != 1) /* error in input */;
Upvotes: 0