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.
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.
– anonimo
Declare your string with length 12.
– anonimo
They never told me that. Thank you!
– Edi Junior
@anonymity that way worked, thank you!
– Edi Junior