0

I'm having trouble with my code below. Before I could input a response [y/n], it just exits the program. I don't see any errors in my compiler so I'm having a hard time fixing this.

   srand(time(NULL));  
    int nGid; //guest id
    char opt1;
    printf(" Hello Guest! do you have an id number [Y/N]?");
    scanf("%c", &opt1);

    opt1 = toupper(opt1);
  //asks for guest id
    if (strcmp(opt1, 'Y') == 0){
        printf("Please enter id: \n");
        scanf("%d", &nGid);
    }
  //generates random id number
    else {
        nGid = rand()%100;
        printf("Your guest id is : %d", nGid);
  return 0;
}

thanks for any help!

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Leila K.
  • 77
  • 6
  • OT: `strcmp()` expects two *pointers* to a `0`-terminated `char`-array, that is two `char*`. The code passes two `char`. Take the compiler's warnings serious. – alk Nov 06 '19 at 12:54
  • To compare two characters just to `opt1 == 'Y' `. – alk Nov 06 '19 at 12:55

2 Answers2

1

strcmp takes null terminated char *, but you are passing char as arguments.

You can directly compare two char using == operator.

Change.

if (strcmp(opt1, 'Y') == 0){

to

if (opt1 == 'Y'){
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
1

Instead of this statement

scanf("%c", &opt1);

use

scanf(" %c", &opt1);
       ^^^

In general instead of

opt1 = toupper(opt1);

it would be correctly to write

opt1 = toupper( ( unsigned char )opt1);

Otherwise the function call can have undefined behavior.

The variable opt1 has the type char. It can not contain a string. So you may not apply the standard function strcmp that deals with strings. Just write

if ( opt1 == 'Y' ){
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Out of curiousity: Why would the cast of `opt1` prevent undefined behaviour? `opt1` is of type `char` already and will implicitely be promoted to `int`, so why the cast? – Anonymous Anonymous Nov 06 '19 at 11:41
  • 1
    @AnonymousAnonymous If the type char behaves as the type signed char then due to the integer promotions the integer value in general can be negative and the call of toupper results in undefined behavior. – Vlad from Moscow Nov 06 '19 at 11:45