1

By using the given source code I am trying to do some arithmetic operations. The given input is:

1
234*34

Since there is no space between 234 and * and 34, scanf is not reading it properly. What should I do so that scanf will read this input and give correct answer without providing the space between the input numbers?

#include <stdio.h>
int arithematic(){
    int a,c,t,i=0,k,l;
    char b[100];
    scanf("%d%s%d",&a,&b[0],&c);
    if(b[0] =='+')
    t = a+c;
    if(b[0] == '-')
    t=a-c;
    if(b[0]=='*')
    t=a*c;
    k=a;
    l=c;
    while(k>0||l>0)
    {
        k/=10;l/=10;
        i++;
    }

    printf("%d\n",a);
    printf("%s",b);
    printf("%d\n",c);

    while(i>0)
    {
        printf("-");
        i--;
    }

    printf("\n%d\n",t);
}

int main(void)
{ 
    int n;

    scanf("%d",&n);
    while(n--)
   {
        arithematic();
        printf("\n");
   }
}
Tom Zych
  • 13,329
  • 9
  • 36
  • 53
  • Use `%c` if it only one char always. (`scanf("%d%c%d",&a,&b,&c);`) and `char b[100];` --> `char b;`. – kiran Biradar Jun 15 '19 at 11:58
  • And put a space before %c to consume optional spaces: https://stackoverflow.com/questions/26391465/why-is-adding-a-leading-space-in-a-scanf-format-string-recommended – basin Jun 15 '19 at 16:23

1 Answers1

0

Replace scanf("%d%s%d",&a,&b[0],&c); with scanf("%d %1[+-*/]%d",&a,b,&c);. The meaning of %1[+-*/] is to consume exactly one character belonging to the set of the four operators. The space preceding it is to consume optional white spaces.

basin
  • 3,949
  • 2
  • 27
  • 63