scanf () при попытке ввести строку с пробелом или без нее закрывает программу - PullRequest
0 голосов
/ 25 января 2019

При попытке ввести scanf(" %[^\n]%*c", &answer); программа зависает на секунду, а затем закрывается, что я могу сделать, чтобы это исправить.

Я пробовал с и без &, с разными способами принятияв пробелах и в разных местах.Это сработало до того, как я включил массив *aarray[] и имел цикл while внутри оператора switch (в полном коде есть несколько случаев с разными вопросами, и я не хотел создавать цикл while в каждом из них).

#include <stdio.h>
void trivia();
int randomquestion();
void main() 
{
  trivia();
}
int randomquestion()
{
    int g;
    g = rand() % 29;
    if(g%2 == 0)
    {
        return g;
    }
    else
    {
        return --g;
    }
}
void trivia(void) {
void *answer;
char *aarray[] = {"","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""};
const char *history[] = { "Which English king was \"mad\"?","George III",
                        "Who started the Protestant Reformation?","Martin Luther",
                        "Who was the first person to see the moons of Jupiter?","Galileo",
                        "What Viking group settled in France before conquering England, Sicily, and Malta?","The Normans",
                        "What group sacked Baghdad in 1258, ending the Islamic Golden Age?","The Mongols",
                        "Against what city did Rome fight the Punic Wars?","Carthage",
                        "What yellow gas was famously used in WWI?","Mustard Gas",
                        "What epic poem is thought to be the oldest in the English language?","Beowulf",
                        "What ancient empire was led by Xerxes, Cyrus, and Darius?","Persia",
                        "Who was the most notorious member of the Ba'ath Party?","Saddam Hussein",
                        "What Italian adventurer wrote about his 24 year journey from Venice to China and back?","Marco Polo",
                        "What young pharaoh's tomb was discovered in 1922?","Tutankhamun",
                        "Before becoming king of England, what country was James I the king of?","Scotland",
                        "What was the primary language of the Byzantine Empire?","Greek",
                        "For what crime was Al Capone convicted of in 1931?","Tax Evasion"
                        };
char y;
int a, g, i = 0, points = 0;
printf("This is a trivia game, choose from History (H), Geography (G), Sport (S) or Technology (T) \n");
printf("There will be 5 random questions, and the user will have to enter the correct answer.\n");
printf("Please enter the letter of your choice. \n");
scanf(" %c", &y);
switch(y){
    case 'H' :
        for(a=0; a<29; a++)
        {
            aarray[a] = history[a];
        }
        break;
    default:
        printf("That was an incorrect input. \n");
        trivia();
}
while ( i <5)
{
    g = randomquestion();
    printf("\n%s :", aarray[g]);
    scanf(" %[^\n]%*c", answer);
    printf("\nYour answer is %s", answer);
    if(strcmp(aarray[++g],answer) == 0)
            {
                printf("\nCorrect!");
                ++points;

            }
            else
            {
                printf("\nIncorrect, the answer was %s.", aarray[g]);
            }
    i++;
}
}

Я ожидаю, что он примет вход и затем продолжит цикл while.

1 Ответ

0 голосов
/ 25 января 2019

scanf(" %[^\n]%*c", answer); пытается записать строку в неинициализированный, нераспределенный (и что более важно) неполный указатель типа void *.

Вам необходимо объявить его как полный тип (т. Е. char *) и выделить для него память либо в стеке, явно объявив размер массива [LEN], либо динамически с malloc(LEN), а затем free it.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...