This question already has answers here:
What does the scanf function return?
(5 answers)
Closed 8 months ago.
can anyone please help me out with this in C language
for ex:
int a = scanf("%d", &a);
doesn't assign the input value to a, but instead gives zero only always.
but this works as intended:
int a;
int a = scanf("%d", &a);
int a;
int a = scanf("%d", &a);
Does not compile because you redefine the variable a twice in the same scope.
scanf("%d", &a) attempts to parse the characters from stdin as the representation of an int and if successful stores the value to a and returns 1, otherwise returns EOF at end of file and 0 if characters are present but do not represent an int value in decimal representation.
Here is an example:
#include <stdio.h>
int main() {
int a, c, res;
for (;;) {
res = scanf("%d\n", &a);
switch (res) {
case 1: printf("value input is %d\n", a);
break;
case 0: printf("input is not a number\n");
break;
case EOF: printf("end of file detected\n");
return 0;
}
// read and discard the rest of the input line
while ((c = getchar()) != EOF && c != '\n')
continue;
}
}
Related
This question already has answers here:
getchar does not stop when using scanf
(5 answers)
Closed 3 years ago.
I started C just a while ago (same as coding), so I`m a noob.
My Goal:
to state that the user hasn't entered a or b and then wait for the user to press enter to return to the calculator menu.
My problem:
getchar() doesn't wait for me to press enter. (Case 3)
#include <stdlib.h>
int main()
{
for (int i = 0;i == 0;){
int options=0,enteredA=0, enteredB=0;
float *a, A, *b, B, *c, C;
a=&A,b=&B,c=&C;
printf ("Calculator\nAvailable options:\n[1]Enter value for A\n[2]Enter value for B\n[3]Addition\n[9]Exit\n");
scanf ("%d",&options);
system ("clear");
switch (options) {
case 1:
printf("Enter a value for A:");
scanf ("%f",&*a);
enteredA++;
break;
case 2:
printf("Enter a value for B:");
scanf ("%f",&*b);
enteredB++;
break;
case 3:
if ((enteredA==0) | (enteredB== 0)){
printf("A and B are not initialized yet. Please enter a value in the menu.\nPress [Enter] to continue to the menu:\n");
fflush(stdin);
getchar();
break;
} else{
printf("%f+%f=%f\n",*a,*b,*c=*a+*b);
fflush(stdin);
getchar();
break;
}
break;
case 9:i++;break;
}
system("clear");
}
printf("Calculator Shut Down");
return 0;
}
In the following line:
scanf ("%d",&options);
you actually enter a number, and a newline character. The scanf function reads only the number. It leaves the newline (\n) in the input stream.
When you call getchar(), it will find a newline in the input stream. Hence, it will read it without waiting for user input. It only wait for user input if it didn't find anything in the input stream.
A possible workaround for this is to call getchar two times instead of one.
The first call will read the already existing newline in the stream. The second call won't find anything in the input stream. So, it will wait for user input as you expect.
I have some small comments that aren't related to your question:
You use scanf ("%f",&*a);. Why not just scanf("%f", a); or scanf("%f", &A); ?
Why you even create a pointer a for the variable A ?
I don't think you really need the variable c as well.
You don't need the variable i in the loop as well.
At the beginning of the loop, you keep re-initializing enteredA and enteredB variables to zero. That way, the condition in case 3: will be always true. You need to move these variables outside of the loop.
Your code also missing a #include <stdio.h>.
I'd simplify things like the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int enteredA = 0, enteredB = 0;
while (1)
{
int options;
float A, B;
printf ("Calculator\nAvailable options:\n[1]Enter value for A\n[2]Enter value for B\n[3]Addition\n[9]Exit\n");
scanf("%d", &options);
getchar(); // The extra getchar to read the newline left in the stdin.
system ("clear");
switch (options)
{
case 1:
printf("Enter a value for A:");
scanf("%f", &A);
enteredA++;
break;
case 2:
printf("Enter a value for B:");
scanf ("%f", &B);
enteredB++;
break;
case 3:
if (enteredA ==0 || enteredB == 0)
{
printf("A and B are not initialized yet. Please enter a value in the menu.\nPress [Enter] to continue to the menu:\n");
}
else
{
printf("%f + %f = %f\n", A, B, A + B);
}
getchar();
break;
case 9:
printf("Calculator Shut Down");
return 0;
}
system("clear");
}
}
This question already has answers here:
How to scanf only integer?
(9 answers)
Closed 4 years ago.
I want to check the user input if it is a number and I want the program to accept only a number as an input. I don't know if I explained myself clearly, I'll try by showing you an example:
int x;
printf("Write a number: ");
scanf("%d", &x);
while(!isdigit(x))
{
printf("Not valid\n");
fflush(stdin);
scanf("%d", &x);
}
I tried using scanf("%d", &x) != 1 as a while condition but it remains inside the loop. Is there a way to ask an input until the user writes a number? For now I just return the function but I'd like not to.
You have to check the return value of scanf():
#include <stdio.h>
int main(void)
{
int x;
while (printf("Write a number: "),
scanf("%d", &x) != 1) // when the number of successful conversion wasn't 1
{
fputs("Not valid!\n", stderr);
int ch;
while ((ch = getchar()) != EOF && ch != '\n'); // clear stdin from garbage
} // that might be left.
}
The code is supposed to ask the user whether to find the sum of numbers from 1 to x or finding the factorial of x. After taking the user's input for the value of x, the program directly ends without running the if and else if statement. This is my code.
#include <stdio.h>
int sum(int num);
int fact(int num);
int main(void)
{
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x);
printf("Enter f for factorial, s for sum \n");
choice = getchar();
//These lines are ignored by C
if (choice == 'f' || choice == 'F')
{
printf("The factorial of %i is %i \n",x, fact(x));
}
else if (choice == 's' || choice == 'S')
{
printf("The sum from 1 to %i is %i \n",x, sum(x));
}
}
int sum (int num)
{
int sum =0;
for (int i =1; i <=num; i++ )
sum = sum+i;
return sum;
}
int fact (int num)
{
int fact =1;
for (int i =1; i <=num; i++ )
fact = fact*i;
return fact;
}
Can anyone please explain to me what is wrong with my code and how can I fix it? Thank you.
I think buffer problem. So, use
scanf(" %d", &x);
^^^
white-space
instead of
scanf("%d", &x);
and also, use
scanf(" %c", &choice);
instead of
choice = getchar();
The problem in this code is in getchar() function.
In first scanning : scanf("%d", &x); when user press enter key, it remain in the input buffer and the integer val is stored in variable x.
In second scanning: choice = getchar();, it reads the enter key in variable choice.
And you have written only two conditions:
if (choice == 'f' || choice == 'F')
else if (choice == 's' || choice == 'S')
That's why it is directly ending the code; as there is no code written for choice = other than 'f' and 's'
if you write 'else' part like this:
else printf("%d", choice);
It will print: 10 which is the ascii value of Enter / New line feed.
To avoid this, try to make following changes in your code:
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x); //here the integer is scanned in variable 'x'
choice = getchar(); //here the enter key is scanned in variable 'choice' so now input buffer is free
printf("Entr f for factorial, s for sum \n");
scanf("%c", &choice); //here the character entered by use will be stored in variable 'choice' so it is overwritten.
This question already has an answer here:
Why is C printing outputs late?
(1 answer)
Closed 7 years ago.
I wrote the following code (it is a caclulator which gets 1 of 3 operators (+/-/$) and 2 natural numbers (a,b) and calcultes (a op b) (a$b is defined to be a+(a+1)+...+(b-1)+b for a<=b and for a>b it is not defined):
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Please choose an operation (+/-/$): ");
char op;
scanf("%c", &op);
while (op != '+' && op != '-' && op != '$') {
printf("\nInvalid operation. Please choose again: ");
scanf("%c", &op);
}
int a;
int b;
char term;
printf("\nPlease enter the first operand: ");
int scanCheck = scanf("%d%c", &a, &term);
while (scanCheck != 2 || term != '\n' || a < 0) {
printf("\nInvalid number\n. Please enter the first operand: ");
scanCheck = scanf("%d%c", &a, &term);
}
printf("\nPlease enter the second operand: ");
scanCheck = scanf("%d%c", &b, &term);
while (scanCheck != 2 || term != '\n' || b < 0) {
printf("\nInvalid number\n. Please enter the first operand: ");
scanCheck = scanf("%d%c", &b, &term);
}
if (op == '$' && a > b)
printf("\nThe result is: Not Valid");
int result;
switch (op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '$':
result = 0;
while (a <= b) {
result += a;
a++;
}
break;
}
printf("\nThe result is: %d", result);
return 0;
}
My problem is that when I run the program it prints nothing. However, after giving the program an input (e.g +, 3, 4) it prints the lines it should have printed earlier (with the correct result). Why does this happen? How can I fix this? FYI I'm using eclipse Juno with minGW compiler.
You may want to add the '\n' at the end of your print statements instead of at the beginning: the buffers may not be flushed and will be delayed because of it.
Output is line buffered. Add a newline at the end of any printout. Or flush the buffer explicitly using fflush(stdout);
For some reason many C programmers like to print newlines at the start of each printout. My advice would be not to do it that way. Just put the newline at the end of each printout, and you'll save yourself lots of trouble:
printf("The result is: %d\n", result);
This question already has answers here:
Check if input is float else stop
(6 answers)
Closed 7 years ago.
So, I'm creating a program that calculates the area of a triangle, and I need it to tell the user if he typed a letter or a negative number, in order, I created the code:
I need to use isdigit
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
int main () {
float a, b, c;
float s=0, ar1=0, ar2=0;
printf("Inform the value of side A.");
fflush(stdin);
scanf("%f",&a);
while(a<=0||isdigit((int)a)){
printf("Invalid value.");
fflush(stdin);
scanf("%f",&a);
}printf("Inform the value of side B.");
fflush(stdin);
scanf("%f",&b);
while(b<=0||isdigit((int)a)){
printf("Invalid value.");
fflush(stdin);
scanf("%f",&b);
}printf("Inform the value of side C.");
fflush(stdin);
scanf("%f",&c);
while(c<=0||isdigit((int)a)){
printf("Invalid value.");
fflush(stdin);
scanf("%f",&c);}
s=((a+b+c)/2);
ar1=(s*(s-a)*(s-b)*(s-c));
ar2=pow(ar1,0.5);
printf("The semiperimeter is %f",s);
printf("The area of the triangle is%f",ar2);
system ("pause");
return 1;
}
But, when I compile/run it, and type "x", or "blabla" when I was supposed to type a number, nothing happens, and the program doesn't warn me, what should I do?
First of all, using fflush on stdin is Undefined Behavior as per the C11 standard, although it is well defined on some implementations.
Secondly, you can't use simply use isdigit that way. Once %f sees invalid data such as characters, the scanf terminates and the corresponding argument is left untouched. Also, using isdigit on an uninitialized variable leads to Undefined Behavior.
What you can do is check the return value of scanf. All the three scanfs in your code returns 1 if successful.
Fixed Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h> //Unused header
void flushstdin() //Removes all characters from stdin
{
int c;
while((c = getchar()) != '\n' && c != EOF); //Scan and discard everything until a newline character or EOF
}
int main () {
float a, b, c;
float s=0, ar1=0, ar2=0;
printf("Inform the value of side A\n");
//fflush(stdin); Avoid this to make your code portable
while(scanf("%f",&a) != 1 || a <= 0){
printf("Invalid value\n");
flushstdin(); //Alternative way to flush stdin
}
printf("Inform the value of side B\n");
//fflush(stdin);
while(scanf("%f",&b) != 1 || b <= 0){
printf("Invalid value\n");
flushstdin(); //Alternative way to flush stdin
}
printf("Inform the value of side C\n");
//fflush(stdin);
while(scanf("%f",&c) != 1 || c <= 0){
printf("Invalid value\n");
flushstdin(); //Alternative way to flush stdin
}
s=((a+b+c)/2);
ar1=(s*(s-a)*(s-b)*(s-c));
ar2=pow(ar1,0.5);
printf("The semiperimeter is %f\n", s);
printf("The area of the triangle is %f\n", ar2);
system ("pause");
return 0; // 0 is usually returned for successful termination
}
Also, it is better to add newline characters at the end of the strings in printf as seen in the above program. They
Improve readability
Flushes the stdout