#problem with scanf
18 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
Please provide some relevant code
!f
!f must be used while replying to a message
!f
#include <math.h>
#include <stdio.h>
#include "hw1.h"
#define NUM_QUESTIONS 20
int main(int argc, char* argv[]) {
int arithmosepilogwn;
char teleutaiaepilogh;
char apanthseis[NUM_QUESTIONS];
char apanthseismath[NUM_STUDENTS][NUM_QUESTIONS];
double poinh;
int a = 0;
do {
printf("Enter number of choices:\n");
scanf(" %d", &arithmosepilogwn);
} while ((arithmosepilogwn > 26) || (arithmosepilogwn < 1));
teleutaiaepilogh = 'A' + (arithmosepilogwn - 1);
printf("Max choice: '%c'\n", teleutaiaepilogh);
printf("Enter answer key:\n");
char ch;
for (a = 0; a < NUM_QUESTIONS; a++) {
int valid = 0;
do {
char ch;
// Read a single character answer from input and ignore spaces
scanf(" %c",
&ch); // The space before %c ensures leading whitespace is skipped
// Skip spaces
if (ch == ' ') {
continue;
}
// Validate the character: Must be between 'A' and the last valid choice
// or '-'
if ((ch >= 'A' && ch <= teleutaiaepilogh) || ch == '-') {
apanthseis[a] = ch; // Store valid answer
valid = 1; // Valid answer, break the loop
} else {
// If invalid, prompt again
printf("Error. Enter value A-%c or '-':\n", teleutaiaepilogh);
}
} while (!valid); // Continue until valid input is given
}
Whats wrong with scanf?
You have scanf accepting a int/number, if the user types in a letter. It will segfault. Use fgets() !
Same with the other scanf()s
it won't segfault. no. it'll just return without parsing it
it seems you redeclared ch in the inner block of that loop for some reason, please remove one of those declarations. other than that - i can't see what the problem seems to be. can you elaborate on what exactly 'isn't working'?
;compile -fanalyzer
<source>:3:10: fatal error: hw1.h: No such file or directory
3 | #include "hw1.h"
| ^~~~~~~
compilation terminated.
Build failed
scanf() blocks (that is, it stops your code and waits) until it has some data to work with, and stdin (the place scanf() reads from) doesnt contain anything until it receives a \n character
eh... not quite. stdin by default is indeed line buffered, but you can change it with setvbuf. in addition the terminal you're using is likely line buffered too, however that can be changed as well
!solved
Thank you and let us know if you have any more questions!
This thread is now set to auto-hide after an hour of inactivity
Really 