While loop stuck infinitely with else statement, despite using continue - c

I'm currently trying to get a users input and see if it is valid, i.e whether or not they have entered an integer versus a string, however, my program does work in realizing the user hasn't entered an integer given it goes to the else statement, except it doesn't restart the loop but rather just prints the words "please try again" a million times in a infinite loop. I've tried implementing the continue statement, but it seems to create the same issue, any input would be much appreciated!
Here is a snippet:
int userInput;
int exit;
exit = 0;
while(exit == 0)
{
if(scanf("%d",&userInput) == 1)
function(userInput);
else
printf("Please try again!\n"); //This loops infinite times, doesn't restart the loop and check input again like the first if
continue;
}

Just add
scanf("%*s");
Inside the body of the else to remove the invalid input from the stdin. You might also want to set exit to 1 when scanf is successful in order to prevent an infinite loop. So modify your code to:
int userInput;
int exit;
exit = 0;
while(exit == 0)
{
if(scanf("%d",&userInput) == 1) {
function(userInput);
exit=1;
}
else
{
printf("Please try again!\n");
scanf("%*s");
}
}

See this answer: https://stackoverflow.com/a/3852934/3788
The original code loops indefinitely because the invalid data (the
"gfggdf") is not removed from the input buffer when scanf fails to
convert it to an integer -- it's left in the input buffer, so the next
call to scanf looks at the same data, and (of course) still can't
convert it to an integer, so the loop executes yet again, and the
results still haven't changed.

Related

why does scanf() not work when followed by a loop?

When I enter a string in the code below, the program doesn't move on. It just allows me to keep typing and pressing enter with no effect. Why does this happen and how can I fix it.
#include <stdio.h>
main() {
char str[20];
int aaa = 0;
int exit;
printf("Enter anything: ");
scanf("%s", str);
while(aaa == 0) {
if(str[3] == 'a') {
aaa++; }
else {
scanf("%d", &exit);
if(exit == 3) {
aaa++; } } }
printf("%s\n", str);
}
Log:
Enter anything: 2/3/4444
Now
it
just
lets
me
keep
on
typing
Edit: I solved it and I’m a bit embarrassed at how simple it was. I know people have been trying to explain this to me but in my own words this is what was happening: as the condition to enter the while loop was being met the program would enter the while loop. However, unless the input entered for the scanf satisfied one of the conditions in the loop, the program had no way of leaving the loop and therefore, it would get stuck. Basically I was simply missing an else statement which solved this problem.
After a string whose fourth character is not an a, your program reads an integer. It will never attempt to read anything but an integer after that first read. So you must not enter anything but an integer after the first string.
If you want your program to handle a non-integer after the string, you need to add code to do that. You currently have none.

Do while loop not exiting despite expression becoming false

I've got a program here which contains a do-while loop within a specified void method. I'm trying to exit the loop within the function, so that the do-while loop actually works as it is supposed to. Except after I run the program and one of the cases occurs, the program continues to run despite my while statement stating that it should only work while(userInput != 1).
I cannot use global variables to solve this problem, as my assignment limits me on using such techniques, thus any help would be much appreciated!
Here is a snippet of my code:
void functionTest()
{
int gameOver = 0;
int userInput;
do
{
printf("please enter a number 1-3");
scanf("%d",&userInput);
switch(userInput)
{
case 1:
printf("You entered %d",userInput);
gameOver = 1;
break;
case 2:
printf("You entered %d",userInput);
gameOver = 1;
break;
case 3:
printf("You entered %d",userInput);
gameOver = 1;
break;
}
}
while(gameOver!= 1);
}
}
The problem probably lies when you use scanf(). Something that you're inputting before hitting enter is not 1, 2 or 3. Could you tell us exactly what you type when it asks you to enter a choice?
Sometimes, the standard output needs to be flushed before using a fresh scanf(). Try fflush(stdout) before the scanf line.
See older question 1 and older question 2.
EDIT:
I can reproduce the problem easily enough if I enter anything apart from "1","2" or "3"...
I would suggest, you do the following before executing the switch statement:
Add fflush(stdout) before scanf()
Accept the input as a string (%s) instead of a number. (char [] needed)
Trim the string of trailing and leading white spaces.
Convert to number using a library function
Then switch-case based on that number
The problem is that if other characters (that aren't part of an integer) are present in the input stream before an integer can be read, scanf() fails and unusable data is never cleared out... which leads to an infinite loop (where scanf() repeatedly fails to read the same characters as an integer, over and over).
So you need to read off the invalid characters when scanf() fails, or as part of the format.
A simple fix would be to change your scanf from:
scanf("%d",&userInput);
to:
scanf("%*[^0-9]%d",&userInput);
to read (and discard) any characters in the input stream that aren't digits 0-9 before reading your integer... but that still doesn't check whether scanf fails for any other reason (like a closed input stream).
You could replace it with something like this:
int scanfRes,c;
do {
scanfRes = scanf("%d",&userInput); /* try to read userInput */
/* ..then discard remainder of line */
do {
if ((c = fgetc(stdin)) == EOF)
return; /* ..return on error or EOF */
} while (c != '\n');
} while (scanfRes != 1); /* ..retry until userInput is assigned */
..which will retry scanf() until the field is assigned, discarding the remainder of the line after each attempt, and exiting the function if fgetc() encounters an error or EOF when doing so.

Infinite loop in C when entered character [duplicate]

This question already has answers here:
Skipping over Scanf statement in C
(4 answers)
Closed 8 years ago.
I am writing an objective c program for hangman. I need to replicate another program which has been given to me. I have done most of it, but am having an issue. It has to replicate the other program exactly, so I went into the other one and entered a character into the wordlength. It came up with the "number must be between 3 and 14 (inclusive)" statement, and asked me to enter a number again, but it started to loop infinitely. It works when i enter a number lower than 3 and larger than 14 (comes up with the error and asks for another input) but with a letter it infinitely loops. Also, the loop is meant to loop infinitely until the word length is larger than 3 and less than 14. That is why the while loop will loop infinitelyAny ideas??? Thanks
while (i == 0) {
printf("\n\n > Please enter a word length: ");
scanf("%i", &wordLength);
printf("\n\n");
if (wordLength > 3 && wordLength < 14) {
continue;
}
else printf("number must be between 3 and 14 (inclusive)");
}
The main problem (that you seem to be asking about) here is that you don't check for errors from the scanf call. It will return with the number of successfully scanned items, or zero if none were scanned, or EOF on error.
If scanf fails to extract data from the input, like when you ask for an integer but the user write a letter, then that letter will continue to be in the input buffer, so the next call to scanf will see that letter again. And again and again...
The best way to fix this is to read the whole line, as text, into a buffer, and then try to parse the integer from this buffer (using e.g. sscanf):
char input[16];
if (fgets(input, sizeof(input), stdin) == NULL)
{
printf("Error reading your input\n");
exit(0); /* Do whatever error handling you want */
}
if (sscanf(input, "%d", &wordLength) != 1)
{
printf("Error: Input was not a valid integer\nPlease try again: ");
fflush(stdout);
continue;
}
Problem is with while (i == 0){ you never change i in the loop. You may want to update it to
while (wordLength == 0){
But make sure you do wordLength=0 before the loop.
change the value of i for the loop to terminate. you dint change the value of i anywhere inside loop.
continue;
will not exit the loop, it will just skip the statement after continue statement and start the loop again. To exit the loop use
break;
so use break or change the value of i to some value other than i=0 to exit the loop.
I think you meant break instead of continue:
if (wordLength > 3 && wordLength < 14)
break;
break will take you out of the loop, whereas continue skips to the next iteration of the loop (which , as others have mentioned, never terminates because i is never changed)
Do not forget to break your loop when the condition is met.
while ( 1 ){
printf("\n\n > Please enter a word length: ");
scanf("%i", &wordLength);
printf("\n\n");
if (wordLength > 3 && wordLength < 14) {
break;
}
else printf("number must be between 3 and 14 (inclusive)");
}

Why code before break doesn't work?

int main() {
int input = 0;
do {
if(input > 1) {
printf("You entered");
break;
}
printf("Enter an integer (> 1): ");
scanf("%d",&input);
} while(input < 2);
return 0;
}
Hello, I'm new to C. Could anyone explain what break does? In this program, the statement before break "You entered" doesn't show up on the console. I know java but this works totally different.
There is no integer exist between 1 and 2. Change
if(input > 1)
to
if(input > 0)
After that if you enter 1 then program enters the if body then print You entered and on encountering the break statement, immediately terminates the do-while loop.
The "break" statement causes your code to exit the loop immediately.
You're not seeing any output because you only loop while the input is strictly less than 2, but your if statement is looking for input that's strictly greater than 1.
That's not going to work; if you enter 1, the if statement won't execute (because 1 > 1 is false), and if you enter 2, the loop exits immediately (because 2 < 2 is false).
You either need to loop while input <= 2, or you need to test for input >= 1.
Having said all that...
Standard output is usually line-buffered, meaning you won't see anything show up on your console until the buffer is full or you send a newline character. You either need to manually flush the stream or send a newline as part of the format string; either
printf("You entered");
fflush(stdout);
or
printf("You entered\n");
should work.

Loop that can take user input every time through

How can I make a loop that can take user input every time it loops?
#include <stdio.h>
#define WORD "jumble"
#define JUMBLED "mleujb"
int main()
{
char string[6];
int i = 0;
printf("The jumbled word is ");
printf(JUMBLED);
printf("\nCan you guess the original: ");
while(i == 0)
{
scanf("%d", string);
if (string == "exit")
{
return;
}
if(string == WORD)
{
i++;
printf("Kudos! You've guessed the word!");
}
else
{
printf("English please, good sir. Guess again.\n");
}
}
}
What I had hoped for was that every time the program went through the loop, it would want a new input with the scanf function. However, that apparently does not work that way. Instead, the program takes the value of the first scanf and uses it over and over again. If it is the wrong word, it will have an infinite loop.
This program has more than a few bugs in it: for instance, it does not actually compare the input to the actual word yet. As that does not pertain to the question, it is not my immediate concern.
you are using scanf() wrongly instead of scanf("%d",string) use scanf("%s",string) as %d is used for decimal input and %s is used for string input
Pseudo code for helping you precisely is not great
Also can you define a bit better your question ? you don't really say what is going wrong
but here is my guess
your test is i ==0 which means as soon as your user inputs the right word your exiting your loop...
I would guess your looking for something like
exit_condition = 0;
while (exit_condition == 0)
{
read keyboard entry
if(condition to exit loop)
{
exit_condition = 1;
printf("correct")
}
else
{
printf("try again")
}
}
Concerning the tests I think you need to read up bit on input and tests
try this
http://www.arachnoid.com/cpptutor/student1.html
scanf is incorrect for getting input string. It should be scanf("%s", string) as pointed out by others
String comparison cannot be done by using == in 'C'. It will only compare the address of two strings which will fail. Use 'strncmp' function instead.

Resources