How to make the below condition fail by giving inputs through stdin - c

void main()
{
float x;
while(scanf("%f",&x) != 0)
printf("%f\n",x);
}
The above code takes input from stdin and keeps repeating it but how to end this? I know scanf can return EOF so if I add a check like
while(scanf("%f",&x) != EOF)
Which input from stdin can cause any of the above two condition to fail?
ctrl+d will make the program end but I want to know is there any specific input which can make this condition fail?

scanf function returns the number of input items successfully scanned.
The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.
In your program always it return 1. To prove see the code..
#include<stdio.h>
main()
{
int a;float x;
while((a=scanf("%f",&x)) != 0)
printf("%f %d\n",x,a);
}
In this program a is always 1. Be cause only one value is scanned successfully.
a gets 2 for , if you scan two values.

Looking at linux manual pages:
scanf: These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
So, using your original program:
void main()
{
float x;
while(scanf("%f",&x) != 0)
printf("%f\n",x);
}
That means that if you enter anything that is not convertible, will end your program. Try it and enter any letter and hit enter

Ctrl + D or Ctrl + Z,
Similar questions already asked before:
End of File(EOF) of Standard input stream (stdin)

Related

Infinite loop when trying to clear the input buffer

OK so after reading these previous questions:
Alternate method for clearing input buffer in c
How to clear input buffer in C?
I came up with a piece of code to empty the input buffer and count how many values were in the buffer, then return this number. A comparison is then made to check if the number exceeded the allowed number.
#include <stdio.h>
#include <stdlib.h>
int Empty();
int main()
{
double x;
int y=0;
while(y==0)
{
y=1;
if(scanf("%lf",&x)!=1 || Empty()>1) //checks if the value is acceppted
// and then attempts to empty
// the input buffer. I always expect
//at least 1 returned due to the
// EOF or '\n'
{
fprintf(stdout,"Invalid character(s) entered, please re-enter.\n");
y=0;
}
}
return(x);
}
int Empty()
{
int clearr,n=0;
do
{
n++;
}while((clearr=fgetc(stdin))!= EOF && clearr !='\n'); // If EOF or '\n' is reached
// it ends, returning the
//number of characters
return(n);
}
If i then run the program and enter 2 or 2.2 etc, the number is accepted and returned.
If i enter 2a, or 2 a or 2 2 etc it always catches the space/letter/etc and forces a SINGLE loop to allow you to try and reenter a value
If, however if enter the offending item, i.e the a, first then an infinite loop occurs.
This does not make sense to me as from what i understand, when the fgetc(stdin) is called it MUST pull either a character or an EOF which would signify only one item has been entered, ending the loop.
In a test if( A || B ), if A is true, B is not evaluated.
So if scanf("%lf",&x)!=1 is true, Empty() is not called and your loop continues forever.
One of the problems here is that you try to do several things at once, the advice would be:
keep things simple
no side effects
So 1) scan the input, 2) if it's ok move on, 3) if it's not flush and repeat.
If you enter a , scanf("%lf",&x) will give 0 and hence it never calls Empty.

Read integers until EOF in C

I need to read all integers until the EOF. I'm trying this code and the problem is that the program doesn't detect the EOF and keeps running. What I need is to receive all the data and proceed to the next line of code automatically (the code works with pressing Ctrl-D after the input).
int x, sum = 0;
while (scanf("%d", &x) == 1) {
sum += x;
}
if (feof(stdin)) {
printf ( "SUM: %d\n", sum );
} else {
printf("ERROR\n");
}
return 0;
How do you want to specify EOF?
^D is the way to do it in the terminal in Unix. In the Windows terminal, ^Z does the same thing. scanf will return -1 and feof() will be non zero. But any further input from stdin will fail too.
Do you want to just hit the enter key? If so, you have to check for that after scanf, otherwise the next call to scanf will read the linefeed and ignore it.
If you type something that is neither white space nor a number, scanf will return 0 and leave the unmatched character in the input stream. Your program will print ERROR. Is this what is happening?

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.

Exiting scanf loop with numbers in one line with one EOF

I have a litte problem with EOF. I need to write numbers in one line with spaces between them and sum them together. Scanf must be ended with one EOF (Ctrl+D)
I have this little program
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv){
double numbers=0, sum=0;
printf("Enter numbers: ");
while(scanf("%lf", &numbers) != EOF){
sum=sum+numbers;
}
printf("\n %.2lf", sum);
}
Problem with this program is that I need to press Ctrl+d two times until it prints sum.
Example input/output:
Enter numbers: 1 3 5 6 <'Ctrl+d'>
15.00
EOF must be preceded with a newline else it won't work. However it depends on the OS. The EOF you enter at the end of of the line containing the input is not recognized. From the man page of scanf -
scanf returns the number of items successfully matched and assigned
which can be fewer than provided for, or even zero in the event of an
early matching failure. The value EOF is returned if the end of input
is reached before either the first successful conversion or a matching
failure occurs.
Therefore you should check the return value of scanf for 1, not EOF.
#include <stdio.h>
int main(void) {
double numbers = 0, sum = 0;
printf("Enter numbers: ");
while(scanf("%lf", &numbers) == 1) {
sum += numbers;
}
printf("\n %.2lf", sum);
}
scanf returns the number of values it assigned; so if you want to use that, you want
while (scanf("%lf", &numbers) == 1)
Alternatively, you could use more of a C++ idiom (assuming you meant to tag the question with that language as well as C):
while (std::cin >> numbers)
The program is showing this behavior because, when you give input
4 4 4 scanf() will not start reading input. scanf() starts reading input when you press [enter]. so if you give input as
4
4
4
then the result will come on first
otherwise you will need 2 's since first one starts reading input and it wont be read as EOF as it just makes scanf() start reading input. therefore one more will be read by scanf() as EOF.
The stdin EOF flag won't be turned on until the second ctrl+d in succession, the first ctrl+d pushes whatever is on your screen to the stdin buffer, the second ctrl+d sets the EOF flag.
In another case, when you enter some numbers and press enter, the numbers on your screen is pushed to the stdin input buffer, and ctrl+d soon after will also set the EOF flag.
On your system this is normal behaviour, the EOF only occurs on the second ctrl+d.

Expected program to print the value of EOF

In the code:
#include<stdio.h>
int main()
{
int t;
for(;scanf("%d",&t);printf("%d",t));
}
The program runs as expected when I give general intergers as input. I am working on Windows so when I scanf Cntrl+Z into the argument t, I do not get the value of EOF i.e -1 on the standard output, but the previous argument that was stored in it.
Also when I press Cntrl + D the program terminates, why does Cntrl+D cause scanf to return 0?
And why on scanf Cntrl+C my compiler says: "Process terminated with status -107......"
I am not understanding why this is happening? Please help.
scanf returns the number of successfully matched formatting specifiers, or EOF if the end of input was reached before matching (or failing to match) the first specifier.
When you press Ctrl+Z, scanf reaches the end of input and returns EOF (because Ctrl+Z terminates input on Windows). This does not terminate your for loop because EOF is nonzero, so the previous value of t is printed (as t was not changed by the call). Note that t will not receive the value EOF on end-of-input as you seem to expect: scanf returns EOF as the return value, it does not write it into the pointers you pass to it.
When you press Ctrl+D, it is treated as any other character. Since it is non-numeric, it causes a matching failure for the %d specifier and scanf returns 0, which terminates the loop.
Try this code and When ever if you press CTL+Z(CTL+D on linux) will give you zero. otherwise prints 1
#include <stdio.h>
main()
{
int c;
while(c=getchar()!=EOF) //here get the character and then compares with the EOF if Not equal 1 will assign to c , if equal 0 will assign to c.
printf("%d",c);
printf("%d",c);//when ever we press ctl+Z(ctl+d on linux) then it will print zero remaing all cases this statement wont execute
getchar();
}

Resources