segmentation fault (if input == var) program compiles
Hey all, this exercise is out of "Beginning C 5th Edition" and it's much easier than working through the Project Euler problems but I am still working on them too. Here is the exercise question:
"The logic of the program is quite straightforward. The program must generate a sequence of integers between 0 and 9 and display the sequence on the screen for one second before erasing it. The program should then read the player’s pathetic attempt to enter the identical sequence of digits. If the player is lucky enough to get the sequence correct, the computer should repeat with another sequence of the same length. If the player’s luck holds out for three successive sequences of a given length, the program should continue by displaying a longer sequence for the player to try. This continues until the player’s luck runs out and he or she gets a sequence wrong. The program will then calculate a score based on the number of successful tries and the time taken and invite the player to play again."
Please, I am getting Segmentaton Fault but program runs fine but cannot get a successful entry to see if there was a match for the scanf entry. This if() statement:
again, this exercise was much easier than the project euler problems but it is preparing me for them (this exercise came out of a chapter on Loops and it's good to freshen up on the nested for loops for the project euler problems) and I haven't even touched K&R yet.
Code:
/* Chapter 4 Exercise from C Programming book 2/14/2020 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
void delay (int seconds) // delay function i got this source code from google
{
unsigned long int count=333333333, i, j;
for(i = 0;i<seconds;i++)
for(j = 0; j < count; j++);
}
int main (void)
{
int limit = 9;
int count, num = 0;
char c = 'X';
int i;
int input = 0;
char newgame;
time_t t;
srand((unsigned) time(&t));
// output text %d\t
for (;;) // game loop
{
printf("\n");
for (count = 1; count <= 9; count++) // generate random number loop digit from 0 -> 9
{
num = rand() % limit;
printf("%d", num);
}
printf("\n");
delay(1); // create 1 second program delay before clear screen with 'X's
// clear screen with x's
for (int ctr_1 = 1; ctr_1 < 7500; ctr_1++)
{
printf("%c", c);
}
printf("\n\n");
printf("What sequence was inserted?: ");
scanf("%d", input);
if (input == num) // corrected answer was inserted
{
// go back to beginning of program for 3 times
/*
for (i = 1; i < 3; i++) // loop for correct answer for 3 times & increase sequence length if true three times
{
;
}
*/
printf("Correct answer!\n");
}
else // answer was incorrect
{
// new games? Yes or no (tolower)
/*
printf("Do you want a new game? (Y or N)\n");
scanf("%c", newgame);
if(tolower(newgame) == 'n') // look for any sign of no (not case sensitive)
{
return 0;
//exit(1); // do this...
}
else // 'y' was inserted
{
// start new game
}
*/
printf("\nError!\n");
}
}
return 0;
}