-1

znak = character
x = number !!

If input is '-' stop, if i run this program it always asks me for 1 more input for number.

int X,i, sumaS=0,sumaD=0;
char znak;

printf("Char and number input:\n");




while (znak !='-'){
    scanf(" %c", &znak);
    scanf(" %d", &X);

    if (znak=='S'){
        sumaS +=X;
    }
    else{
        sumaD+=X;
    }
}

Test case:

S 7

D 5

S 2

S 2

D 3

D 7

-

Equus
  • 37
  • 6
  • 1
    Because you're taking input before checking the previous of whether to exit or not. You can just place a break before the second scanf – Irelia Nov 02 '19 at 18:24
  • If I do that, program will stop after i input char element – Equus Nov 02 '19 at 18:26
  • Equus, what value do you think `znak` has the very first time `while (znak !='-'){` is executed? – chux - Reinstate Monica Nov 02 '19 at 18:33
  • Can i put random char in znak to check value for the first time, and then i can use scanf and my inputs? – Equus Nov 02 '19 at 18:35
  • How about ending when there is no number input on a line? For that you would however have to drop your (anyway unwise) habit of ignoring the return value of scanf(). – Yunnosch Nov 02 '19 at 19:54

1 Answers1

-1

How about initializing znak to zero at the beginning ? (It is better for avoiding problems sometimes. Try in the scanf() to use it without space. use scanf("%c", &znack) instead of scanf(" %c", &znack). (Don’t foger to use fflush(stdin) for cleaning the input buffer between 2 iterations for avoiding to get the \n in znack)

Yoni Melki
  • 205
  • 3
  • 16