The trouble is that white space (including newlines) in scanf()
format strings behaves peculiarly — it means an arbitrary sequence of white space characters.
When it prompts Nome:
, you can type a name ('Alexander the Great') and a newline, but the scanf()
keeps reading until it comes across another character that isn't white space. So, you might type 'Conqueror of Asia', and then the prompt Descricao:
will appear, and it will read until you type another character that isn't white space, and then it will terminate.
For example:
$ ./name-prompt
Nome: Alexander The Great
Conqueror of Asia
Descricao: a
<<Alexander The Great>> - <<Conqueror of Asia>>
$
This is from the code:
#include <stdio.h>
#include <stdlib.h>
struct s_Especialidade{
char nome[60];
char descricao[60];
struct s_Especialidade *proximo;
};
typedef struct s_Especialidade Especialidade;
typedef Especialidade *PESPECIALIDADE;
static
void novaEspecialidade(void)
{
PESPECIALIDADE novo = malloc(sizeof(Especialidade) );
printf("\nNome: ");
if (scanf("%59[^\n]\n", (novo->nome)) != 1)
printf("Oh, bother!\n");
printf("\nDescricao: ");
if (scanf("%59[^\n]\n", (novo->descricao)) != 1)
printf("Oh, bother!\n");
novo->proximo = NULL;
printf("\n<<%s>> - <<%s>>\n", novo->nome, novo->descricao);
free(novo);
}
int main(void)
{
novaEspecialidade();
return 0;
}
Note that the printf()
output ends with a newline; that's generally a good idea.
To work around this, modify the scanf()
format to:
"%59[^\n]"
After the scanf()
, do the equivalent of:
int c;
while ((c = getchar()) != EOF && c != '\n')
;
Package it into a function — maybe gobble()
or read_to_newline()
.
Or use fgets()
to read the line and sscanf()
to parse it; that often works better.