In my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
void flushstdin()
{
int c;
while((c = getchar()) != '\n' && c != EOF);
int main () {
float a, b, c;
float s=0, ar1=0, ar2=0;
printf("Inform the value of size A.");
while(scanf("%f",&a) != 1 || a <= 0){
printf("Invalid value!");
What does "while(scanf("%f",&a) != 1 || a <=0){" means?
Well, scanf returns either the number of arguments matched in the given pattern (the %f part) read, or a -1 if an EOF was encountered (meaning end of input). Then a <= 0 should be somewhat self explanatory. These two combined this code will result in an input loop until either the user enters a value greater than 0 or nothing at all.
For more information on scanf, check out the docs: http://www.cplusplus.com/reference/cstdio/scanf/
This attempts to reads a float from stdin and checks whether the float was successfully read (scanf returns the number of arguments successfully read). If a was read successfully, it checks whether a is larger than zero. It continues until both conditions are false. The second condition will only be evaluated when the first condition is false, i.e. a has been read.
scanf() returns number of elements successfully read and in this case you are expecting the number of elements read to be 1. If the conversion fails then the value will not be 1 so you print out invalid value, the scanned value a can't be less that or equal to 0
scanf("%f",&a) is use for input value in your program , and here your condition is loop keep going until you enter 1 or nagitive value
While scanf returns a float (%f) e.g. 4.535 and stores it into variable a (&a) that is not equal to 1 or (||) a is equal to or less than zero (a<=0)
Related
I have two pieces of codes to test how the two console I/O functions, getchar() & scanf(), handle the EOF. But I still do not have a clear comprehension about the actual operations behind the outputs and their behaviors. Can someone explains that for me? Thanks a lot! (I am using Windows OS)
// 1st piece of Code
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
while ((ch=getchar()) != EOF)
{
putchar(toupper(ch));
}
return 0;
}
If I type
abc
or
abc(ctrl+z)
The program will have the same outputs:
ABC
// 2nd piece of Code
#include<stdio.h>
int main(void)
{
int x;
while(scanf("%d",&x) != EOF)
{
/*Ctrl + z + Enter*/
printf("x=%d\n",x);
}
return 0;
}
If I type
123
The program will output:
x=123
Otherwise, if I type
123(ctrl+z)
The program will have an infinite output:
x=123
x=123
x=123
x=123
...
getchar() returns the value of the character converted to unsigned char or EOF in case of error.
The error can be "end of file" or something else; usually (for getchar()) the programmer does not care about the error, just that an error happened.
scanf() returns the number of values matched and assigned (basically the number of % in the format string) or EOF in case of error. Note that the number can be less than the number of % in case, for example, of badly formatted input
Just like for getchar() the error can be "end of file" or something else. Particularly, reading less than the number of % is not an error.
So you may prefer to test for the correct number of assignments rather than testing for error in scanf()
#include <stdio.h>
int main(void) {
int x;
while (scanf("%d", &x) != 1) {
/*Ctrl + z + Enter*/
printf("x=%d\n", x);
}
return 0;
}
The problem is that on Windows the EOF is put into the input buffer like a normal character (with the encoded value 26).
When reading character by character (with e.g. getchar) this is handled by the Windows run-time library. But it doesn't work like that with scanf because when scanf parses the input it's like another character. And as a non-digit it's an invalid character for te "%d" format, leading to your scanf Call to return 0 instead of EOF (since it's not parsed by the format).
One way to solve it is to press the Ctrl-Z sequence on its own new line.
Another (and more reliable) way to solve it is to check that scanf returns the number of formats you have in the string. In your case you should compare against 1 (as you have one format specifier).
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.
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)
I have this simple code (trying to do an exercise in KandR):-
#include <stdio.h>
int main(){
int c = EOF;
while(c=(getchar() != EOF)){
printf("%d",c);
}
return 0;
}
When i run this and enter any character (a single character), i get the output as 11. If i enter multiple characters for example 'bbb' i get the output as 1111. I understand that i have explicitly added brackets to give precendence to the condition check of getchar() != EOF which should either result in 1 or 0. But i don't understand why am i getting multiple 1's.
Another case is:
#include <stdio.h>
int main(){
int c = EOF;
while(c=(getchar() != EOF)){
putchar(c);
}
return 0;
}
No matter which character i enter, i always get the output as a square box with 1's and 0's in it (shown at the bottom of the screenshot below)
1) In the first case, why is the output printing more than 1 1's?
2) Why isn't the output of case 2 same as case 1?
Until unless you press EOF, (getchar() != EOF) will return true which assigns 1 to c. That's why you are getting output always as 11, first 1 for the character you entered and second 1 is for \n passed to the input buffer on pressing Enter key.
Similarly in case of putchar it prints the character corresponding to the returned value 1 which is non-printable (printable characters start from 32) and you will get some weird output, one for input character and another for \n.
Now change the parentheses in conditional expression to
while( (c=getchar()) != EOF ){...}
Now it will work as it should but will give you two ASCII code in first case (one for \n).
1) In the first case, why is the output printing more than 1 1's?
Because you are looking for an EOF. In order to send your program EOF from the keyboard, press Ctrl+Z
2) Why isn't the output of case 2 same as case 1?
Because %d produces a decimal representation of the character code, while putchar produces the character itself. For example, if you print 'A' using printf's %d format, you would see 65 - ASCII code of the uppercase character A. On the other hand, if you print it using putchar, you would see character A itself.
Demo on ideone.
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.