I am writing a text-based game in C. At the start of the program, it prompts you if you want to start or end the game. However, when I type end or start, it brings up a "Segmentation Fault" error. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//Variables
char *name, *answer ;
//Beginning of program
int main()
{
//Game starts and prompts you
printf ("--|| YOUR_ADVENTURE_HERE ||-- \n") ;
printf (" \n") ;
printf ("Type 'START' to start the game or 'END' to end the game. You can end the game at any point by typing it as well.") ;
scanf ("%59s, answer") ;
//If typed 'START'
if (answer = "START")
{
printf ("\n") ;
printf ("Starting game...") ;
sleep (5) ;
return 0 ;
}
//If they typed 'END' (this will be used in every scanf)
if (answer = "END")
{
system("exit") ;
return 0 ;
}
Here is also how it looks when I run it:
--|| YOUR_ADVENTURE_HERE ||--
Type 'START' to start the game or 'END' to end the game. You can end the game at any point by typing it as well.START
Segmentation fault
Thanks in advance!
Allocate memory to pointer before trying to store anything there.
scanf ("%59s, answer") ;
should be preceded by a memory allocation for answer
answer = malloc(60);
scanf ("%59s", answer) ;
Also, on a side note, use strcmp to compare strings.
if (answer = "START")
should be
if (!strcmp(answer,"START"))
The problem is here:
scanf ("%59s, answer");
First, scanf requires a list of arguments to write values obtained from input. You haven't provided any. Instead, you have only one long string. Surely what you meant was:
scanf ("%59s", answer);
But even that won't work.
It requires that answer be allocated memory of some kind, and not be an uninitialized pointer. This will work better:
char answer [60];
scanf ("%59s", answer);
I didn't look any further for other problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With