Reputation: 105
I am trying to sum some integers and when I press '=' the loop will terminate and print the sum of those values. I am trying to give a space before press equal.
#include <stdio.h>
int main()
{
int a, sum = 0;
char b;
while (1) {
scanf("%d", &a);
scanf(" %c", &b);
sum += a;
if(b == '=')
break;
}
printf("sum = %d", sum);
return 0;
}
Upvotes: 0
Views: 98
Reputation: 44274
The two scanf
, i.e.
scanf("%d", &a);
scanf(" %c", &b);
will work like this:
Input: "1 2 3 4 ="
In the first loop a
will become 1 and b
will become 2.
In the second loop a
will become 3 and b
will become 4.
Now the remaining string is " ="
So in the third loop there is no integer to scan and consequently a
will still have the value 3. b
will get the value =
and the loop terminates.
So sum
is 1 + 3 + 3, i.e. 7
You can check that using simple printf
statements:
scanf("%d",&a);
printf("a=%d\n",a);
scanf(" %c",&b);
printf("b=%c\n",b);
Input:
1 2 3 4 =
Output:
a=1
b=2
a=3
b=4
a=3
b==
sum= 7
Remember: Always check the value returned by scanf
- like:
if (scanf("%d",&a) != 1)
{
// Error - didn't scan an integer
// add error handling
...
}
So you can do
while(1){
if (scanf("%d",&a) != 1)
{
// No integer found
// Add error handling...
// For now - just stop the loop
break;
}
sum+=a;
}
For input like "1 2 3 4 =" this give the result 10.
However, input like "1 2 3 4 HelloWorld" will also give the result 10, i.e. any non-integer input simply terminates the loop. If you only want the loop to terminate when the input is =
, you can extend the error-handling.
Upvotes: 2
Reputation: 2085
Your issue is because you are doing scanf twice in your loop.
Do this instead:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int sum=0;
char a[10];
while(1){
scanf("%9s", a); // makes sure we won't have memory overflow
if(strcmp(a, "=") == 0)
break;
sum+=atoi(a);
}
printf("sum= %d",sum);
return 0;
}
Upvotes: 1