Receive multiple strings in the same row in C

Asked

Viewed 556 times

-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

  • 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.

  • 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'.

2 answers

0

There is no need to use dynamic allocation for your program, since the value is constant and even if you decide to continue using dynamic allocation, defining constants is a recommended practice to reduce the likelihood of future errors.

int main(void) {
   const int TAMANHO = 200;

   char *name = malloc(TAMANHO * sizeof(char));
   char *city = malloc(TAMANHO * sizeof(char));

   // Você pode trocar as duas linhas acima pela alocação estática abaixo:
   //char name[TAMANHO], city[TAMANHO]; 

   fgets(name, TAMANHO, stdin);
   name[strlen(name) - 1] = '\0';
   
   fgets(city, TAMANHO, stdin);
   city[strlen(city) - 1] = '\0';
   
   //Você também pode imprimir o que deseja com apenas uma chamada da função printf
   printf("%s %s\n",name, city);

   //Caso aloque estaticamente você pode eliminar os frees abaixo
   free(name);
   free(city);
   return 0;
}

The getchar function reads a character and can be used so that the ' n' that is left in the input buffer does not interfere with the reading of strings or subsequent characters. In your example there is no need to use it because the fgets function already reads this ' n' and inserts it into the string (which you are already dealing with with the command immediately after reading).

-1


Using the fgets() function you will always have a new line between the items as it always adds ' n' on the console by pressing enter on the keyboard.

To get the desired behavior, you can use the scanf() function and the ',' character to separate the two strings.

See the example code below:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {

  char *name = malloc(200 * sizeof(char));
  char *city = malloc(200 * sizeof(char));

  scanf("%200[^,]s",name);
  scanf("%200[^\n]s",city);

  printf("%s%s",name,city);

  free(name);
  free(city);

  return 0;
}

Thus, the first scanf will insert in the name variable all the characters you type until you find the character ',' (with ' 0' at the end). The second scanf will insert all characters into the city variable until it finds the character ' n', inserting ' 0' at the end. So you could type: João da Silva, Campinas [enter] to assign the strings in the same line.

Note the first parameter of the scanf() function: "%200[ ,]s" 200 represents the maximum number of characters (must be compatible with the size of your char vector), [^,] represents that the string will be terminated when the character ',' is found in the standard input and s represents the data type read, in case a string.

  • Thiago, thanks for the scores, I managed to make the necessary correction in the code and in fact the result was better. About the last part of my question, I’m going to ask for your help again. I understand how to make the loop for the repetition to happen, but I wouldn’t know how to input data on the same line. For example: João da Silva. Campinas. That still eludes me the ability.

  • Hello William, I updated the answer to give you a way about entering the data on the same line. You will not be able to get the same result using fgets() as this automatically inserts a ' n' and there will be a line jump.

  • This is exactly what I needed Tiago, thanks for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.