#menu selection infinite loop
40 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.
@misty locust
Your message appears to contain screenshots but no code. Please send code and error messages in text instead of screenshots if applicable!
int menu(struct info data[], long int count){
int X;
printf("What do you want to do?\n");
printf("1. Display Data\n");
printf("2. Search Data\n");
printf("3. Sort Data\n");
printf("4. Export\n");
printf("5. Exit\n");
printf("Your choice: ");
scanf("%d", &X);
if(X == 1)
display(data, count);
else if(X == 2)
search(data, count);
else if(X == 5)
return 0;
else{
printf("error, not found!");
return menu(data, count);
}
return menu(data, count);
}
https://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
The first argument to
scanf()is a format string, describing whatscanf()should parse. The important thing is:scanf()never reads anything it cannot parse. In our example, we tellscanf()to parse a number, using the%dconversion. Sure enough,abcis not a number, and as a consequence,abcis not even read. The next call toscanf()will again find our unread input and, again, can't parse it.
what is a parse ;-;
yes, do something like this:
while (scanf("%d", &x) != 1)
Also it looks like your file in c++. If you're in c++, you have easier options for user input
Your file ext is cpp
the name of the app is just dev c++
Oh
what does this do? O_O
it will make sure the user enters valid input
because scanf returns an int
if it is 1 it means it failed
wait dont that mean i need an index
index of what?
no, scanf takes in the address of x
ye
so whatever you input, x will get replaced with it
and if scanf sees that you entered in a character for example
it will return 1 indicating a failure
which is why while (scanf("%d", &x) != 1) checks for that
where do i put it tho
where youre calling scanf
That check alone won't fix it. That will only tell you if it failed. There are still the unread characters in the buffer, and it will infinitely loop like before. I highly recommend reading this guide to learn how to safely take user input-- there are a lot of pitfalls
do something like this:
while (scanf("%d", &x) != 1)
{
while (getchar() != '\n')
{ }
printf("FAILED\n");
}
the inner loop of "getchar" will clear the input buffer
what if i just do X != 1, 2, 3, 4, 5 then print error
it worked :D tysm
@misty locust Has your question been resolved? If so, type !solved :)
!solved