C - for loop only execute ones after scanf [closed

2019-09-21 08:42发布

问题:

The for loop runs only once, after entering my answer with scanf, the for loop terminates. I have no idea why?

for(int i = 0; i < 10; i++){  
    char answer;  
    gotoxy(32,10);  //self-made function(using Dev C++) to go to a coordinate
    star_vowels(easy[i]);    
    gotoxy(30,18);  
    printf("ANSWER: ");  
    scanf("%s", &answer);  
}  

回答1:

The answer variable is defined as character so you should change the format string of the scanf function:

scanf("%c",&answer);


回答2:

The problem is likely because of your buffer overflow.

You define a variable answer that can store just one char. Yet you pass it to scanf to scan a string. If you just enter one character and press enter, you already overflow answer and likely overwrite i in the process which then becomes larger than or equal to 10.

You need to pass a buffer (like char answer[100]; or dynamically allocated with malloc) to scarf. Using scanf to scan a string correctly is a bit tricky.

If you really only meant to read a single character instead, @klyone's answer is the correct one: use the %c format string.



回答3:

One issue would be that you are using scanf to input a string, however answer is a single character.

Even if you are only entering a single character string, it will be attempting to put that character in the string, followed by a null byte.

Assuming a 1 charcater answer, changing the 'char answer' to 'char answer[2];' and changing the scanf() to scanf("%1s", answer); may help



回答4:

Assuming you want to read in a string as opposed to a single character, I would highly recommend using fgets instead of scanf to read your input, as it will ensure that you never get a buffer overflow of any sort, as far as I recall.

Also, as others have said, you will first need to allocate more than one character for the answer, either by statically allocating it or doing it dynamically with malloc and free. Assuming you want to save the answers somewhere, doing dynamic allocations would be necessary. If you only need it one time, allocating it statically like char answer[100]; would suffice. Although I would recommend putting something like #define BUFFER 100 at the top of your file, and allocating it like char answer[BUFFER]; instead.



标签: c for-loop scanf