Reputation: 187
I'm new to C Programming and I am stuck on a simple problem. Here is the following code...
#include <stdio.h>
/* Write a C Program that accepts two integers from the
user and calculate the sum of the two intergers. Go to the editor!
*/
int main()
{
int firstInteger, secondInteger;
int sum;
printf("Input two Integers: \n");
scanf("%d%d", &firstInteger, &secondInteger);
sum = firstInteger + secondInteger;
printf("%d", sum);
return 0;
}
After I run my code on the GCC compiler I don't get what I expect!
C:\XXXX\XXXX\XXXX\XXXX\XXXX>gcc 2sumOfTwoIntegers.c
C:\XXXX\XXXX\XXXX\XXXX\XXXX>a
Input two Integers:
25, 38
25
Why don't I get the sum of my inputted Integers?
Upvotes: 0
Views: 1235
Reputation: 310950
You are expecting that the user will enter two integers using a comma between them. The user can enter two integers like for example
25,38
or
25, 38
or
25 , 38
or
25 ,38
All these inputs are valid. You need to process the input correctly.
What you need is to skip the comma between the two numbers.
Also take into account that the sum of two integers can be too big to be stored in an object of the type int.
Here is a demonstrative program that does the task.
#include <stdio.h>
int main(void)
{
int firstInteger, secondInteger;
printf( "Input two Integers (first , second): " );
if ( scanf( "%d %*c %d", &firstInteger, &secondInteger ) == 2 )
{
long long int sum = ( long long int )firstInteger + secondInteger;
printf( "The sum of the integers is %lld\n", sum );
}
else
{
puts( "Incorect input." );
}
return 0;
}
Its output might look like
Input two Integers (first , second): 25 , 38
The sum of the integers is 63
Another approach is to read the comma in a variable and check that the user indeed typed a comma. In this case the program can look like
#include <stdio.h>
int main(void)
{
int firstInteger, secondInteger;
char c;
printf( "Input two Integers (first , second): " );
if ( scanf( "%d %c %d", &firstInteger, &c, &secondInteger ) == 3 && c == ',' )
{
long long int sum = ( long long int )firstInteger + secondInteger;
printf( "The sum of the integers is %lld\n", sum );
}
else
{
puts( "Incorect input." );
}
return 0;
}
Upvotes: 1
Reputation: 144
You have two ways to solve this problem -
scanf("%d,%d", &firstInteger, &secondInteger);
[Note: what you give inside %d it will skip in the input section. Like you want to take two integer hour and minutes in two variables. Then you can write:
scanf("%d:%d", &hour, &minute);
So that if you write in the input section - 10:30 then the hour variable take 10 and the minute variable take 30. ]
Upvotes: 1
Reputation: 76
You are putting comma in input. Just put a single space Like that 25 38
Upvotes: 1
Reputation: 75062
scanf()
don't skip ,
in the input by default and stop there because it cannot be interpreted as integer.
Add ,
to the format like this to have scanf()
read and drop ,
.
scanf("%d,%d", &firstInteger, &secondInteger);
Upvotes: 0