-2
I have the following code that gets the keyboard input and prints on the screen what was typed.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *name = malloc(50 * sizeof(char));
char *city = malloc(50 * sizeof(char));
fgets(name, 50, stdin);
fgets(city, 50, stdin);
printf("%s %s",name,city);
free(name);
free(city);
return 0;
When I try to type a name followed by a city, line breaks occur with each string I try
Behavior occurred on the console:
João da Silva,
Campinas
Expected behaviour:
João da Silva, Campinas
My question is to understand why my code behaves this way (why line breaking after entries occurs) and how I would do to make these entries (need to be different variables) on the same line, without I need to break the line for such.
What is the point of allocating memory to store 5 characters and then using the fgets function to read up to 200 characters? I don’t understand the point of you using this gaetchar. The fgets function setting says it will read characters until it finds an ' n' or the maximum number of characters specified in the function. See: https://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html
– anonimo
In the case that I’m a beginner, some criteria are not yet clear to me, I should probably, instead of putting 200, 5*sizeof.
– Guilherme
Another point to consider is
name[strlen(name) - 1] = '\0';
. The goal is to replace the ' n' character that was incorporated at the end of the string read by the fgets function Pelao character ' 0' which indicates the end of the string, however if the string in the input is larger than the specified size (200 in your case) this character ' n' will not exist in your string. The best would be for you to check if the last character is ' n' and if it is then replace it with ' 0'.– anonimo