Locke Cai
Locke Cai

Reputation: 15

C If statement Error: exited with non-zero status

I'm new to c, and I am trying to make a typing game.But the if statement doesn't work,and the output is "exited with non-zero status".May be the problem is cause by the IDE,I can't figure it out,thanks.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main (void)
{
  char start;
  printf ("here is a typing game\n");
  printf ("type any key to start\n");
  scanf ("%c", &start);
  void game()
  {
    int i;
    char answer;
    char type[20];
    {
      for (i = 0; i < 20; i++)
      {
        printf ("%c", 'a' + (random() % 26));
      }
    }
    scanf ("%s", answer);
    if (strcmp(answer,type) == 0)
    {
      printf ("good\n");
    }
    else
    {
      printf ("so bad\n");
    }
  }
  game();
}

Upvotes: 0

Views: 4628

Answers (2)

Pushan Gupta
Pushan Gupta

Reputation: 3825

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

void game();

int main (void)
{
  char start;

  srand(time(NULL));//seed rand function with time to generate "near to pseudo random numbers"(note: This is not "really" pseudo anyways!)
  printf ("here is a typing game\n");
  printf ("type any key to start\n");
  scanf("%c",&start);
//define your function outside main
  game();//call your function here
}   
void game()
  {
    int i;
    char answer[20];//answer should also be an array
    char type[20]="";//initialize type this way to avoid unnecessary characters initialization

    {
      for (i = 0; i < 19; i++)//should be 19 not 20... Last character has to be null
      {
        printf ("%c", type[i]='a' + (rand() % 26));//You forgot to add the random characters in type array and 
                                                   //rand should be called this way

      }
    }
    scanf ("%s", answer);
    if (strcmp(answer,type) == 0)
    {
      printf ("good\n");
    }
    else
    {
      printf ("so bad\n");
    }
  }

Suggestion: Improvisations should still be made, like taking input using fgets() and not scanf and managing answer array overflow at input.

Upvotes: 0

Govind Parmar
Govind Parmar

Reputation: 21542

There are a number of things wrong with this code.

  1. You can't have a function inside another function (as you have with game defined in main).

  2. answer is a single char, not a string, so to read it with scanf you need to use the line scanf("%c", &answer); - if what you wanted was to read a single character, that is; from the rest of your code it seems you intended for answer to be a string, so you'd have to declare answer to be a char [20] array and call scanf with the "%s" format specifier.

  3. You can't use strcmp to compare a char to a string. strcmp is for comparing strings to strings, not strings to characters or characters to characters. Furthermore, you never assign a string to the array type anywhere in your code.

Upvotes: 1

Related Questions