String scanf() time problem

Asked

Viewed 87 times

0

I wanted a help in solving the problem of a string, because when you read the program automatically from as invalid option any option, so you do not use the option I chose. No if I’ve tried with && instead of || and also did not give.

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

int main()
{
 char sexo[2];

 printf("---Sexo---\n");
 printf("1 - Masculino\n");
 printf("2 - Feminino\n");
 setbuf(stdin, NULL);
 fgets(sexo,2,stdin);
 if(sexo[2]!='1' || sexo[2]!='2')
 {
   printf("\nOpção Inválida\n");
   system("PAUSE");
   sexo[2]=0;
 }
 return 0;
}
  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

2 answers

3

It makes no sense to read this way, ask for a whole and be happy. Understand that these standard C console mechanisms, especially reading, exist only to do very basic things and in real code people use mechanisms of their own or libraries that perform this more properly. The purpose of using them is only to support exercises and experiments, so use them as simply as you can to avoid these difficulties.

#include <stdio.h>

int main() {
    printf("---Sexo---\n");
    printf("1 - Masculino\n");
    printf("2 - Feminino\n");
    int sexo;
    scanf("%d", &sexo);
    if (sexo != 1 && sexo != 2) printf("\nOpção Inválida\n");
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • The program I am doing will have to compare a sex variable to another sex2, if I use as integer value instead of string, and when comparing will work using If ?

  • Yes, even better. If you insist on char you can do it too, but it takes work to do it right, you have to start worrying about the difficulties of C dealing with this type of data entry, it’s a complication for exercise.

1

Well, there are some errors in your code. Assign 1 or 2 to the sex variable, so it has to be int and not char. Char is for characters, unless you use a function that converts from char to int. Then in if, since sex is int type does not need ' '.

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

int main()
{
 int sexo;

 printf("---Sexo---\n");
 printf("1 - Masculino\n");
 printf("2 - Feminino\n");
 scanf("%d",&sexo);
 if(sexo!=1 && sexo!=2)
 {
   printf("\nOpção Inválida\n");
   system("PAUSE");
 }
 return 0;
}

Browser other questions tagged

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