Problem: I have two strings, if I fill all the positions of the first string, it concatenates with the value of the second string

Asked

Viewed 34 times

0

A simple algorithm to compare two cpfs:

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

int main(){
    char cpf[11], cpfBusca[11];

    for(int i = 0; i < 11; i++){
        cpf[i] = '\0';
        cpfBusca[i] = '\0';
    }

    printf("Digite seu CPF: ");
    fflush(stdin);
    gets(cpf);
    system("cls");
    printf("Digite o CPF para comparacao: ");
    fflush(stdin);
    gets(cpfBusca);
    system("cls");

    if(strcmp(cpf, cpfBusca) == 0) printf("O CPF esta cadastrado.\n");
    else printf("O CPF nao esta cadastrado!\n");

    //só para conferir
    printf("%s\n", cpf);
    printf("%s\n", cpfBusca);

    system("pause");
    return 0;
}

With an online compiler (usually compiled with gcc), I saw that the value ended up being concatenated and this only happens when I fill in all 11 characters of the first string, why is this happening? Another algorithm I did a few days ago worked out, but I went to test it again and the same problem happened, I’m confused.

  • 1

    In C a string is an array of characters plus the terminator character ' 0'. So to store a Cpf number of 11 positions you will need to declare a string of 12 positions. In your case probably the first entry wrote the terminator character outside the memory area reserved for it (occupying the first position of the second Cpf), when reading the second Cpf the terminator character was overwritten by the first character of the second Cpf and the terminator character was also written outside the area reserved for it but that was not overwritten by any other variable.

  • 1

    Declare your string with length 12.

  • They never told me that. Thank you!

  • @anonymity that way worked, thank you!

No answers

Browser other questions tagged

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