Reputation: 33
In this program the objective is to create an evaluation of workers to catalogue them by risk factor. I have declared a function to evaluate every one of the questions that would make the profile of the workers.
The thing is, I don't know what went wrong while declaring the function, and I don't even know if that's exactly the problem.
My code goes well up to statements about "peso" and the program succesfully asks the user the value and also seems to be stored inside the variable. But, when the function is called to be assigned to the diabetes variable the value of peso becomes zero and then, when the function is called again to be assigned to hipert, the diabetes value seems to flush, because it wouldn't print it.
#include <stdio.h>
#include <stdlib.h>
char resp(char tempo[1], char op_1[1], char op_2[1]);
int main(void){
char sexo[1];
int edad;
int peso;
char pre[0];
char diabetes[1];
char hipert[1];
printf("Calculadora de factor de riesgo - COVID19.\n");
printf("Ingresa los datos que se te pidan.\n");
printf("Ingresa tu sexo (m/f): ");
sexo[0] = resp(sexo, "m", "f");
printf("\nIngresa tu edad (mayor o igual a 18): ");
scanf("%d", &edad);
while(edad<18){
printf("\nRespuesta no aceptada. Intenta de nuevo. ");
scanf("%d", &edad);
}
printf("\nIngresa tu estado de peso (bajo (1), normal (2), sobrepeso (3), obesidad (4)): ");
scanf("%d", &peso);
while(peso != 1 && peso != 2 && peso != 3 && peso != 4){
printf("\nRespuesta no aceptada. Intenta de nuevo. ");
scanf("%d", &peso);
}
printf("\nPadeces diabetes? (s/n): ");
diabetes[0] = resp(diabetes, "s", "n");
printf("\nPadeces hipertension? (s/n): ");
hipert[0] = resp(hipert, "s", "n");
printf("%s", sexo);
printf("%d", edad);
printf("%d", peso);
printf("%s", diabetes);
printf("%s", hipert);
}
char resp(char tempo[1], char op_1[1], char op_2[1]){
scanf("%s", &tempo[0]);
while (tempo[0] != op_1[0] && tempo[0] != op_2[0]){
printf("\nRespuesta no aceptada. Intenta de nuevo. ");
scanf("%s", &tempo[0]);
}
}
Upvotes: 1
Views: 58
Reputation: 75062
sexo
(passed as tempo
) has only one element, so it can store only upto zero-character string (plus terminating null-character) and passing it for %s
is dangerous.resp
is assigned to sexo[0]
, but no return
statement is in resp
and using its return value will invoke undefined behavior.To fix, at least the lines
char sexo[1];
char diabetes[1];
char hipert[1];
sexo[0] = resp(sexo, "m", "f");
diabetes[0] = resp(diabetes, "s", "n");
hipert[0] = resp(hipert, "s", "n");
should be
char sexo[2];
char diabetes[2];
char hipert[2];
resp(sexo, "m", "f");
resp(diabetes, "s", "n");
resp(hipert, "s", "n");
Also there are more points to improve such as:
%1s
instead of %s
for scanf()
.scanf()
should be checked.resp()
should be void
to mark that the function doesn't return anything.Upvotes: 2