0

Getting next line near country?

#include <stdio.h> #define max_size 57 int main(void){ int bags, weight; bags = weight = 0; //Longest know country name is 56 characters char country[max_size]; printf("What country did you fly in from?\n"); fgets(country, max_size, stdin); printf("How many bags did you have?\n"); scanf("%i", &bags); printf("What was the total weight of all bags?\n"); scanf("%i", &weight); printf("I flew from %s having %i bags with average weight of %i\n", country, bags, weight/bags); return 0; }

10th Sep 2021, 2:05 PM
Sri
Sri - avatar
3 Respuestas
+ 1
Thanks I got it!!!
10th Sep 2021, 2:42 PM
Sri
Sri - avatar
0
fgets gets every character in the input stream up to a max that you set. If the country name is less than 57 characters, fgets will swallow the '\n' character when RETURN is pressed to enter the country name. There's probably a way to do it with fgets but i prefer scanf. Change the line to: scanf("%s", country); // and you'll get your expected output
10th Sep 2021, 2:37 PM
Slick
Slick - avatar
0
scanf("%s", country) allows for buffer overflow someone typing 58 characters will crash the program. That is why I suggested fgets as previously stated.
11th Sep 2021, 8:55 PM
William Owens
William Owens - avatar