0

I'm pretty new in C. My problem is the code keep looping at that line ( you can check the code) while what i wanted is for it to loop the whole for statement, not a single line.

English is not my first language so i'm truly sorry

#include <stdio.h>
int hw;
int uts;
int uas;
float hasil_uts;
float hasil_uas;
float hasil_hw;
char opsi;
int main (void) {
    int n1; //Homework
    int c1;
    for (c1=0;opsi != 'n';c1++) {
      printf ("Input : ");
      scanf ("%d",&hw);
      n1 += 1;
      hasil_hw += hw;
      printf ("\nInput another marks? (y/n)"); // it loops here when it run
      scanf ("%c",&opsi);
    }
 return 0;
}

1 Answers1

3

you have to add one space in scanf like this scanf (" %c",&opsi); ,otherwise you will take \n as your character in scanf.

also note that you are using uninitialized variable n1 and hasil_hw. you have to add n1=0 and hasil_hw=0 to your code.

also as mentioned in comments you should check scanf returned value.

look

int hw;
int uts;
int uas;
float hasil_uts;
float hasil_uas;
float hasil_hw=0;
char opsi;
int main(void) {
    int n1=0; //Homework
    int c1;
    for (c1 = 0; opsi != 'n'; c1++) {
        printf("Input : ");
        if ( scanf("%d", &hw) != 1) 
      { 
         fputs ("error: invalid value.\n", stderr); 
          return 1;
      }
        n1 += 1;
        hasil_hw += hw;
        printf("\nInput another marks? (y/n)"); // it loops here when it run
        if (scanf(" %c", &opsi) != 1)//add space before %c 
      { 
         fputs ("error: invalid value.\n", stderr); 
          return 1;
      }
    }
    return 0;
}
hanie
  • 1,863
  • 3
  • 9
  • 19
  • Some explanation: most of the format specifiers for `scanf` automatically filter leading whitespace, but `%c` and `%[...]` and `%n` do not. Adding a space in front of the `%` instructs `scanf` to filter leading whitespace here too. – Weather Vane Mar 29 '20 at 20:24
  • @WeatherVane sorry a lot , I first wrote `scanf` for character then copy it for integer ,and I didn't notice the comment. – hanie Mar 29 '20 at 20:27
  • You got my vote. – Weather Vane Mar 29 '20 at 20:28