So, I'm new to C and this is my ever first project for class. I basically need a program that asks the user how many questions he wants, then retrieves a positive max 8 bit number which can be in oct/dec/hex (it's random) and then asks the user to convert it to to a random base. For example, If I get a decimal number It will randomly ask me to convert it to hex or octal. At the end of every question, it says if my convertion is right or wrong and in the end of the program it shows how many questions I got right.
All works well until I start typing random letters/characters when it asks me to convert to other than hex. If it asks me to, for example, convert octal to decimal, if I enter a single letter it will sometimes say It's right and it also skips questions and continues the cycle until it gets an hex.
I can't really figure out what can I do. Here's my code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int rightanswers = 0;
int answer;
int nquestions;
printf("Number of questions:");
scanf("%d", &nquestions);
srand((unsigned int) time(NULL));
unsigned char questions[nquestions];
for (int i=1; i<=nquestions; i++)
{
questions[i] = (rand()%255)+1;
int randomnumb = (rand()%6)+1;
switch(randomnumb)
{
case 1:
printf("\nConvert 0%o to base 10:", questions[i]);
scanf("%d", &answer);
if (answer == questions[i])
{
rightanswers++;
printf("Right!");
}
else
{
printf("Wrong!");
}
break;
case 2:
printf("\nConvert 0%o to base 16:", questions[i]);
scanf("%x", &answer);
if (answer == questions[i])
{
rightanswers++;
printf("Right!");
}
else
{
printf("Wrong!");
}
break;
case 3:
printf("\nConvert %d to base 8:", questions[i]);
scanf("%o", &answer);
if (answer == questions[i])
{
rightanswers++;
printf("Right!");
}
else
{
printf("Wrong!");
}
break;
case 4:
printf("\nConvert %d to base 16:", questions[i]);
scanf("%x", &answer);
if (answer == questions[i])
{
rightanswers++;
printf("Right!");
}
else
{
printf("Wrong!");
}
break;
case 5:
printf("\nConvert 0x%x to base 8:", questions[i]);
scanf("%o", &answer);
if (answer == questions[i])
{
rightanswers++;
printf("Right!");
}
else
{
printf("Wrong!");
}
break;
case 6:
printf("\nConvert 0x%x to base 10:", questions[i]);
scanf("%d", &answer);
if (answer == questions[i])
{
rightanswers++;
printf("Right!");
}
else
{
printf("Wrong!");
}
break;
}
}
printf("\nYou got %d conversions right!", rightanswers);
return 0;
}