Infinity loop in while statement - c

Here is a snippet from my code
scanf("%d", &s);
while(s!=1 && s!=2) {
if(scanf("%d", &s) != 1) {
show_warning(); //just print some info msg
}
}
The idea is to execute show_warning function only if user enter something different of 1,2 and entered value to be only integer.
With the code above it jumps in infinity loop. How to fix that ?

The problem is that the failed input operation doesn't extract any characters from the stream (and you'll keep reading the invalid input over and over), so you have to empty the input manually. For example:
char buf[1000];
// ...
if(scanf("%d", &s) != 1)
{
puts("Error, try again: ");
fgets(buf, 1000, stdin);
}
As I suggested in the other question, if you use fgets from the start to always read one line and process it later, you overcome this problem.
(The same philosophy is true in C++: read the whole line first so the input stream can move on, and process the line later to see if its valid.)

Why are you using a while loop? Do you want show_warning(); to be called once, or repeatedly? If you answered once then you only need an if-statement.

What makes you think it is looping until infinity?
You only get the warning message when you have not entered a number because it did not read a token.
Changing the && to || though is a certain way to ensure it will run to infinity as your loop will never break then.
You might want an alternative message to prompt the user to enter data when they did enter a number but not 1 or 2?

I'm assuming you're having issues when a non-integer is input. This is because scanf leaves non-matching characters in the buffer, so subsequent calls are seeing the same input and looping.
What you need to do is if the scanf call returns any number other 1 is: read that character in using scanf("%c",&somechar) so you can print it and tell the user that it isn't accepted. The non-accepted input will then have been removed so the next call to scanf will give you the next input rather than the one you saw on the previous iteration.

Also what happens when no scanf succeeded? The variable s remains unchanged (and perhaps with an undefined value, if you did not initialize it). You should set it, or change the condition of the while !
And you really should learn to compile with warnings enabled and debugging information (i.e. gcc -Wall -g on Linux) and to use a debugger (e.g. gdb on Linux)

Related

Checking if input is a ENTER without losing the first character in C

I have a program with alot of data stored in a file and gets loaded into structs.
I have an option so the user can change some information but since I don't know what he wants to change I need to printf and scanf all the information of the item he wants to change.
This is a part of the program:
char check;
if(p->vetor.id == jogo){
printf("Reference: %d\n", jogo);
fflush(stdin);
printf("\nTeam 1: ");
if(getchar() != '\n'){ // METHOD 1
gets(p->vetor.eqTeam1);
}
fflush(stdin);
printf("\nTeam 2: ");
if(scanf("%c", &check) && check != '\n'){ //METHOD 2
gets(p->vetor.eqTeam2);
}
fflush(stdin);
}
It checks if the input is a ENTER (and it works) but when I write something there it "eats" the first letter because it needs to check before if is a ENTER or not, is there a way to give the lost letter back to the gets() ?
Thanks for your help.
It checks if the input is a ENTER (and it works) but when I write something there it "eats" the first letter because it needs to check before if is a ENTER or not, is there a way to give the lost letter back to the gets() ?
The function ungetc() is probably what you're looking for.
However, cleaning input buffers is a recurrent topic in C. Be aware that fflush(stdin) is a Undefined Behavor, because it actually makes no sense : flushing a buffer doesn't drop its content, it actually triggers its immediate shipping toward its final destination, which is, in case of an input buffer… yourself !
Some systems take advantage of this non-defined behavour situation to actually drop it as expected (which is an undefined behavour just like anything else), but this is a trap because the programmer get used of doing something that is not supposed to work. To my eyes, the most consistent behavor here is to do nothing, since the buffer's content is already available to the reader.
Don't use scanf and never again use gets.
Your problem can be solved by just using fgets
printf("\nTeam 2: ");
fflush(stdout);
char input[256]; // same size of eqTeam
fgets(input, sizeof(input), stdin);
if (input[0] != '\n') {
strcpy(p->vetor.eqTeam2);
}
This will always read in a full line, but if the first character of the line is a newline, the user just pressed enter. If the first char is something else, the input is copied to the correct location. Note that the input buffer must be of a suitable size, here I just guessed one that is for sure not correct (but I lack the necessary info)
And one more thing, never flush stdin, you have to fflush(stdout) as fflush is an output operation.

scanf for string and number in C

I've been trying to use scanf() for reading string and integer. It works fine, but I am unable to check if the input is given correctly.
char command[6];
int cmd_num;
scanf("%5s %d", command, &cmd_num);
It works fine for reading the right input, I am able to check if the string is right by strcmp. I tried to check the number by the function isdigit(), but it cannot check correctly, I guess because of whitespaces, but I am not sure exactly how it works.
I tried to google this, I played around with [^\n] but still it doesn't work. Could anyone enlighten me how scanf exactly works please?
I think solution would be if I exactly could tell scanf what to read ->string(space)integer. Is it possible to acquire this with regular expressions or any other way?
What I need basically is to scanf read the line recognize the string and then to check if there is a number after it too.
Another question is, I need to read the input for as long as the user is giving it, I tried to use getchar for while loop, to repeat as long as the char is not '\n' but this closes the loop right in the beginning, but if I give it EOF condition it never ends even with multiple newlines. I guess it could be limited by the scanf too, but I am not sure exactly how, threads on this forum couldn't give me the answer for it.
This will not procced:
while ( ( c = getchar() ) != '\n')
{
//code
}
This will proceed no matter of newlines:
while ( (c = getchar() ) != EOF )
{
//code
}
You don't check if a number is a number, and isdigit() is used to check if an ascii value is a number between 0 and 9.
To check that scanf() succeeded and the input is correct, thus the value of cmd_num is correct and is an integer read from the input, you have to check the return value of scanf().
It returns, the number of matched format specifiers. You have two of them so
if (scanf("%5s%d", command, &cmd_num) == 2) // this means it's correct
// ^ your code is missing the address of operator

C Ending a loop with user input

I'm trying to write a program that lets the user insert integer values into an array until they enter a specific key to stop, say ENTER, or X.
int array_numb[100];
char quit = 'x';
printf("Enter as many values into the array as you want, pressing x will end the loop\n");
while(1==1){
int i = 0;
scanf("%i",&array_numb[i]);
i++;
array_numb[i] = quit;
}
I know it's wrong but this is my thought process. Any ideas? thanks for the help
Enter as many values into the array as you want while having int array_numb[100];, at some point you will be in trouble. What if the user enters more than 100 numbers before entring the sentinel value? You'll be overruning the allocated memory, isn't it?
You should check the return value of scanf() to ensure proper input. A mismatch in the supplied format specifier and the type of input will cause scanf() to fail. Check the man page for details.
You need to have a break statement inside while(1) loop to break out. Otherwise, you need to have a conditional statement in the controlling expression for while() loop to terminate the loop.
Note: IMHO, the best way to stop scanning user input is to comapre the return value of scanf() against EOF, which can be produced by pressing CTRL+D on linux and CTRL+Z in windows.
You can check this answer for your reference.
The same thing can be achieved as shown below:
scanf() can fail and check the return value. When a character is scanned scanf() fails
int i=0;
printf("Enter as many values into the array as you want, pressing x will end the loop\n");
while(i<100 && scanf("%d",&array_numb[i])==1)
{
i++;
}
scanf, with %i, will fail to scan a number when invalid data, such as a character is inserted and will return 0(in your case) if it fails.
Just check the return value of scanf. If it is zero, use
if(getchar()=='x') //or if(getchar()==quit)
break;
Note: Clear/flush the standard input stream(stdin) using
int c;
while((c=getchar())!='\n' && c!=EOF);
after the loop as well as after the break; .
You could learn something and use signals:
http://man7.org/linux/man-pages/man7/signal.7.html
Register SIGINT, override it, let it check which key was pressed, then let it change a variable. In your loop check if this variable is 0 or 1.
Signals have top priority, signal code will be executed no matter the loop.
Example: http://www.thegeekstuff.com/2012/03/catch-signals-sample-c-code/
It's overkill for this case but a fun thing to know. Signals are the way how an OS is managing events, like process kills, keyboard input etc. Be warned, how to use this is OS specific and has not much to do with C itself.

scanf() is getting skipped

Hi
Just started learning c for uni (usually use objective c) and have run into a strange issue with scanf, i have the following code
while(stringCheck == 0){
scanf("%c",&computerType);
computerType = toupper(computerType);
if ( computerType == 'L') {
/*set stringCheck to 1 so the scanf while loop breaks*/
stringCheck = 1;
counter = 0;
} else {
printf("ERROR\n");
}
}
This i printing out "ERROR" then asking for input (so it is skipping the scanf statment the first time). If i change the it to another variable that is a string it works fine, it stops on the first time.
The rest of the code works fine, its just the fact that it print an error as soon as it enters the loop that is annoying.
I have tried getChar() and it does the same thing.
Thank you for any help you have to offer.
If it's printing an error the first time you enter the loop, then there's already something in the input buffer. I'll guarantee (assuming your compiler is not brain-dead) that it is not skipping the scanf. You should check what it's actually receiving by changing:
printf("ERROR\n");
to:
printf("ERROR, code = %02x\n", computerType);
I would suggest that it's the newline from the last time your program ran that code (you say it's the first time but it's unclear as to whether you mean the first time into that loop ever (since program started) or first time entering that loop but you've been through it before on this program run.
When you enter LENTER the first time, your code will pull out the L but not the ENTER. If you then call that code again, it will get the ENTER key.
You should either understand and allow for what's actually entered or use a safe and sound input function like this one.
You should always check the return value from scanf(); it tells you how many of the conversions succeeded. In this context, if you don't get back 1, you have a problem. The first time around the loop, scanf() reads a character - but not an ell (l or L) because you say you get an error message. The next iteration attempts to read the newline or whatever else follows the previous erroneous character, and the newline is certainly not an ell, and the other characters quite likely aren't an ell either, thus producing at least one more error message. You would get an error printed for each non-ell character.
Generally, if you use scanf(), it is fairly hard to recover from errors. You're likely to be better off reading a line into a buffer (character array) and use sscanf() to parse it.
You should just need to add a space before %c. I am unsure why it works, but it does. This also happens with other data types.
Replace your scanf statement with scanf(" %c",&computerType);

Scanf and loops

here a a piece of code that is supposed to loop over and over until the user inputs a number between 0 and 15
int input;
do
{
printf("Enter a number => ");
scanf("%d",&input);
printf("\n %d \n",input);
}
while (!(input>0 && input <15));
However if the user puts in something like "gfggdf" it results in the loop repeating over and over and over and never prompting the user for input again... the console looks like this
Enter a number =>
0
Enter a number =>
0
Enter a number =>
0
Enter a number =>
0
Enter a number =>
0
Enter a number =>
0
(looping indefinitely)
After looking through this book, it seems I need to do something like this to prevent this from happening.
int input, error, status;
char skip_ch;
do
{
error = 0;
printf("Enter a number => ");
status = scanf("%d",&input);
printf("\n %d \n",input);
if(status!=1)
{
error=1;
}
else if(input < 0 || input >15){
error = 1;
}
do
{
scanf("%c",&skip_ch);
}while(skip_ch != '\n');
}
while (error);
I understand needing to check for the scanf status to make sure it was valid input, What I don't understand the the inner do-while loop. I feel like the book never really explained to me why scanf needs to be called several times like that, it's like somehow the scanf buffer got filled up with a bunch of garbage and it's somehow cleaning it out by just looping through it a million times for you.
Could anyone please explain this black magic to me?
That's why there are so many answers to similar questions that recommend not using scanf().
Also, you should check the return value from scanf() because it tells you when something has gone wrong - and no value could be converted.
The normal recommended solution is a combination of fgets() to read lines of input and sscanf() to parse the line once it is read.
The second loop in your example goes around reading the characters up to and including a newline, thus resynchronizing scanf() and skipping any bogus data. It is a long-winded way of doing it; it would be simpler to use getchar() instead:
int c;
while ((c = getchar()) != EOF && c != '\n')
;
Note the use of 'int c;' - the type is crucially not 'char' or 'unsigned char' because it must store all possible char values plus EOF.
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.
The:
do {
scanf("%c",&skip_ch);
}while(skip_ch != '\n');
simply reads one character at a time (and ignores it) until it gets to the end of the line. If you prefer to get rid of the garbage in the input buffer without a loop, you can use something like: scanf("%*[^\n]");
Another possibility that's (probably more) widely used is to start by reading an entire line, then attempting to convert what's in the line. Whether it converts or not, you've already read all the data to the end of the line so the next attempt at reading/converting will start from the next line whether the conversion worked or not. This does have one potential weakness: if you got a really long line of input, you could end up reading and storing a lot of data for which you have no real use. It's rarely a big deal, but you should still be aware of it.
First of all, avoid using scanf(), use fgets() instead.
To evaluate your condition (first code). 0 > 0 is false. 0 < 15 is true. false && true is false. !false is true. That's why it's looping indefinitely.

Resources