Actually, I'm learning C langage and I have written a programm
Enter the value of 2 numbers as shown below.
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d", &a, &b);
printf("Sum of the numbers = %d\n", c);
return 0;
}
But if I enter an alphabet I'm getting some 1522222 numbers. Instead of
this I want it throws an error as invalid input if I type alphabet ie a,b,c.
How could I do that?
You can check the return value of scanf. If it is successful, it should return 2, since you're reading two values. If you get anything else, you know that the input is incorrect. Try this:
if (scanf("%d%d", &a, &b) != 2)
printf("Invalid input type!\n");
else
printf("Sum of the numbers = %d\n", a+b);
On a different note, you don't initialize c anywhere, so printing it is undefined behavior. You don't even need c for this, you can just print a+b instead.
Related
I am fairly new to C and I am having trouble using scanf with pointers. I have been told to get user inputs for 3 int and 1 char values and then print them back out using pointers.
This is the best I could come up with so far:
int a, b, c;
char d;
int *x = &a;
int *y = &b;
int *z = &c;
char *e = &d;
scanf("Enter 3 Ints and 1 Char:%d %d %d %c", x, y, z, e);
printf("The numbers are:\n");
printf("%d\n %d\n %d\n %c\n", a, b, c, d);
return 0;
When I enter the values the following is printed out:
2 3 4 c
The numbers are:
32708
-613084440
32708
�
Again, I'm very new to programming so I apologize if this is a stupid mistake or something obvious that I have missed.
You are not checking the return value of your scanf, otherwise you would know that it returns 0, as in 'no elements read'.
Your scanf expects you to write exactly what you are putting in there, so, if you entered Enter 3 Ints and 1 Char:2 3 4 c, it would probably work.
What you want, however, is this:
printf("Enter 3 Ints and 1 Char: ");
if (scanf("%d %d %d %c", &a, &b, &c, &d) != 4)
printf("Invalid input detected\n");
else
printf("The numbers are:\n%d\n %d\n %d\n %c\n", a, b, c, d);
The first line will print the prompt to the console, the second will read the values into variables.
There is no need to create separate pointer variables for this purpose.
// program to detect whether only integer has been given or not
int main() {
int a, b, s;
printf("Enter two proper number\n");
BEGIN:
s = scanf("%d %d", &a, &b); //storing the scanf return value in s
if (s != 2) {
printf("enter proper value\n");
goto BEGIN;
}
printf("The values are %d and %d ", a, b);
}
This program to detect whether only integer has been given or not goes into infinite loop when invalid data is entered instead of asking for new values
why doesn't the goto work here?
Note that when scanf gets bad input (for example you enter cat dog) that input remains in the input buffer until you take steps to clear it out. So the loop keeps repeating and rejecting the same input which is still there.
It is simpler to use fgets and sscanf and if the scan fails, you just forget the input string and get another.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a, b;
char str[42];
do {
printf("Enter 2 numeric values\n");
if(fgets(str, sizeof str, stdin) == NULL) {
exit(1);
}
} while(sscanf(str, "%d%d", &a, &b) != 2);
printf("Numbers are %d and %d\n", a, b);
}
Program session:
Enter 2 numeric values
cat dog
Enter 2 numeric values
cat 43
Enter 2 numeric values
42 dog
Enter 2 numeric values
42 43
Numbers are 42 and 43
Note that goto is poor practice in C and should be used only where there is no other way of constructing the code — which there usually is.
There are multiple reasons scanf() can return a value different from 2:
there is pending input that cannot be converted according to the conversion specification. For example if there is an A pending in the input stream, the %d conversion fails and the A stays in the input stream. Your code just keeps trying this conversion and will never stop. You should read and discard the offending input before re-trying.
the input stream has had a read error or hit the end of file. If at least one conversion succeeded, the number of successful conversions is returned, otherwise EOF is returned. If EOF is returned, there is no point trying again since no more input will be available.
Note also that it is considered bad style to use goto for constructions that are better expressed with flow control statements such as while and for.
Here is a corrected version:
#include <stdio.h>
// program to detect whether only integer has been given or not
int main() {
int a, b, s, c;
printf("Enter two proper numbers: ");
for (;;) {
s = scanf("%d%d", &a, &b); //storing the scanf return value in s
if (s == 2) // conversions successful
break;
if (s == EOF) {
printf("unexpected end of file\n");
return 1;
}
/* discard the rest of the input line */
while ((c = getchar()) != EOF && c != '\n')
continue;
printf("Invalid input. Try again: ");
}
printf("The values are %d and %d\n", a, b);
return 0;
}
scanf returns the number of characters. As a result, s will be equal to the number of characters you have written is 2, then your loop will stop. The reason this runs infinitely many times is that the number of characters you have entered differed from 2. Print s to see what value it holds and you will get more information.
Ignoring the fact that negative numbers would not work here, why do positive integers create a infinite loop? I tried many combinations, as simple as a = 20 and b = 4, but every single one creates a infinite loop. What am I doing wrong or not seeing here?
#include <stdio.h>
int mdc(int a, int b) {
while (a != b) {
if (a > b)
a = a - b;
else b = b - a;
}
return a;
}
int main() {
int a, b;
printf("Valores mdc: \n");
scanf("%d %d\n", &a, &b);
printf("%d\n", mdc(a,b));
return 0;
}
Not an infinite loop for the given input:-
The thing is you have used \n in the scanf as a result unless you enter some non-whitespace character - it waits for it.
What did the '\n' do?
From standard explaining the why part - C11 N1570 §7.21.6.2¶5
A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails.
How to give input then?
So it will work if you do this:-
>>> 20 4 Enter
<Somenonwhitespace> Enter
Better solution:
Even better suggestion would be to use
scanf("%d%d", &a, &b);
You don't need to specify the space as you did - %d directive skips over the white space characters.
Code wise
if(scanf("%d%d", &a, &b)!=2){
fprintf(stderr,"Error in input\n");
exit(EXIT_FAILURE);
}
If you were to step the code in a debugger you would discover that the while loop is never even entered. It is not a problem of an infinite while-loop. Rather that scanf() never returns.
Change:
scanf("%d %d\n", &a, &b);
to
scanf("%d %d", &a, &b);
The line scanf("%d %d\n", &a, &b); should be scanf("%d %d", &a, &b); no \n.
I want to calculate sum of arithmetic progression in which we have to take 3 variables from user. a=first number, b= step size/increment, c=length of sequence.
If there are more than 1 test case , say three, then I have to scan a,b,c three time. How to do this?
E.g scanf (" %d %d %d", a,b,c); 3 times without affect initial values in first test case.
If you know no of test cases read it first and store it in a variable.
int calculate_ap(int a, int b, int c)
{
//Implement function to calculate Arithmetic progression and return the result
}
int main()
{
int test_cases = 0;
int a, b, c;
scanf("%d", &test_cases); //Reads no of test cases
while(test_cases--)
{
scanf("%d, %d, %d", &a, &b, &c); //read A, B, C
printf("%d\n", calculate_ap(a, b, c));
}
}
Hope this helps.
I would like to know where is my mistake.
When scanning the parameters as doubles , and immediately printing them (for checking), the print is not giving me the values that I entered.
I tried to define them as integers and it worked, but for doubles its just giving me this: a=0.00000, b=-0.00000
take a look:
#include <stdio.h>
#include <stdbool.h>
int main()
{
double a=0,b=0,c=0;
scanf("%lf",&a);
scanf("%lf",&b);
scanf("%lf",&c);
printf("%lf %lf\n",a,b);
return 0;
}
EDIT: sorry i didnt include my whole code , this is the whole code, but it still gives me the same thing.
Written as it is, your program will accept correctly formatted input for 3 floating point values and will print the first two.
What values do you enter?
What is the precise input you type into your program?
I suspect you type extra characters: scanf stops scanning on invalid input.
You should test the return value from the scanf function calls and verify that values were actually parsed.
Incidentally, the printf format for double arguments is %f, not %lf, but this should not pose a problem as the extra l is most likely ignored.
Here is a corrected version you should try to find out where the problem lies:
#include <stdio.h>
int main(void) {
double a = 0, b = 0, c = 0;
if (scanf("%lf", &a) != 1) {
printf("invalid input for a\n");
}
if (scanf("%lf", &b) != 1) {
printf("invalid input for b\n");
}
if (scanf("%lf", &c) != 1) {
printf("invalid input for c\n");
}
printf("a=%f b=%f\n", a, b);
return 0;
}