Search code examples
cstringstdio

scanf when reading string not giving expected result


I a new programmer at C and I'm struggling with problems involving string, I have the following code:

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
#define MAXNOME 60


typedef struct aluno
{

    char codigo[5];
    char nome[MAXNOME];
    char cpf[11];
    char periodo[6];

} aluno;

void adicionaAluno(){

    aluno novoAluno;

    // adiciona codigo do aluno 
    printf("\nDigite o codigo do aluno: "); 
    scanf("%s", novoAluno.codigo);
       
    // adiciona cpf do aluno
    printf("\nDigite o CPF do aluno: ");
    scanf(" %s", novoAluno.cpf);

    printf("\nDigite o periodo do aluno: ");
    scanf(" %s", novoAluno.periodo);

    // adiciona nome do aluno
    printf("\nDigite o nome do aluno: ");
    scanf(" %[^\n]", novoAluno.nome);
    printf("%s\n", novoAluno.nome);
    printf("%s\n", novoAluno.cpf);
    printf("%s\n", novoAluno.codigo);
    printf("%s\n", novoAluno.periodo);
}

int main(){
    adicionaAluno();
    return 0;
}

When I run it with the following input:

Digite o codigo do aluno: 19404

Digite o CPF do aluno: 11122233344

Digite o periodo do aluno: 2020.1

Digite o nome do aluno: Bruno Mello

I would expect it would return:

Bruno Mello
11122233344
19404
2020.1

But instead, it returns:

Bruno Mello
111222333442020.1
19404Bruno Mello
2020.1

I simply can't understand why this is happening, can someone explain why this code isn't working and how can I fix it?


Solution

  • char cpf[11]; should hold space also for a terminating character '\0'. So in your case it should be at least 12.

    In memory, after cpf comes periodo, which when scanned overidses cpf[11], which coincides with periodo[0] which results in seeing 111222333442020.1 printed. Note the same applies for periodo, only you don't have another variable that you override after it.