Problems:
- Using the wrong function to read the string.
- It is not comparing the string, but the address where it is.
- Little space in the matrix.
- Not iterating as often as necessary.
Starts by organizing the size of the matrix:
char nome[5][20];
int i;
In a matrix like this, what you have is 5 lines and 20 columns, and the name Marcos de Oliveira has at least 18 characters, which should be ideal.
puts("Entre 5 nomes :");
for(i=0; i< 5 ; i++)
{
scanf("%19[^\n]%*c",nome[i]);
}
In this part you may not use the printf
with \n
, the puts
is much simpler. Naturally the scanf
stops reading when finding an empty space when using in conjunction with the %s
, using that expression %19[^\n]%*c
makes empty spaces used.
for(i=0; i < 5; i++) {
if(!(strcmp(nome[i], "Lucas de Oliveira"))){
printf("\nNome: %s\nIdade : 18 anos, \nSexo : Masculino, \nEstado civil : Solteiro", nome[i]);
break;
}
}
Here, just change the expression in the arguments of if
using the function strcmp
which compares two expressions, and returns 0
where they are identical, and also i < 1
for i < 5
which is the size of the matrix, otherwise it stops at the first iteration, and does not advance to the remaining names, and of course, remove the continue
and put break
in place, so iteration stops when finding the match.
Using fgets
As an alternative to the expression within the scanf
, you could use the fgets
:
for(i=0; i< 5 ; i++)
{
fgets(nome[i], 26, stdin);
}
Like the fgets
keeps breaking \n
, should be removed in order to be able to compare with the desired word.
for(i=0; i < 5; i++) {
if ((strlen(nome[i])>0) && (nome[i][strlen(nome) - 1] == '\n')){
nome[i][strlen(nome) - 1] = '\0';
}
if(!(strcmp(nome[i], "Lucas de Oliveira"))){
printf("\nNome: %s\nIdade : 18 anos, \nSexo : Masculino, \nEstado civil : Solteiro", nome[i]);
break;
}
}
If none or any of the functions used here are not working, check the documentation for alternative, or check the compiler settings in use.
You cannot compare strings directly in C. In this case, you are comparing the memory region between the constant and the content in
nome
. Study the functionstrcmp
ofstring.h
: http://www.cplusplus.com/reference/cstring/strcmp/– Jefferson Quesado
The command
continue
is being used in the wrong way. Whenever possible, let the loop follow its normal flow without interfering in its execution.– Jefferson Quesado
But the strcmp function works also for arrays ? Because when trying with it, the error.
– Mondial
How did you test it? And what you call a mistake?
SIGSEGV
?– Jefferson Quesado