1

I'm pretty new with c, the problem is when it reaches a certain line, the program freezes. i have no idea why and how to fix it. is there anything wrong with my code or is it the terminal that's broken?


#include <stdio.h>
#include <time.h> 
#include <string.h>
#include <stdlib.h>

float cinta;
float benci;
float hasil;

char nama [100];
char pacar [100];
char tanya;

int main(){

    printf("hallo, selamat datang di game seberapa cinta anda! \n");
    printf("siapa nama anda? ");
    scanf ("%s \n",nama);
    printf ("Siapa nama pacar anda? ");
    scanf ("%s \n",pacar);
    printf ("Apakah anda siap untuk di kalkulasi? ");
    scanf ("%c \n",tanya); // here's the line
    if ((tanya == 'y')||(tanya == 'Y')) {
        srand(time(0));
        cinta = rand() %100 +1;
        benci = rand() %100 +1;
        hasil = cinta + benci;
        printf ("selamat \n");
    } else { 
        hasil = 0.0;
    }
   printf("Your love is at %f percent", hasil);
   return 0;
}
  • 2
    `scanf ("%c \n",tanya); // here's the line` ==> `scanf(" %c", &tanya);` – pmg Mar 05 '20 at 08:29
  • 1
    activate warnings on your compiler: with `gcc -Wall`, you'll get: `warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=] scanf ("%c \n",tanya); // here's the line` – Mathieu Mar 05 '20 at 08:30
  • Frank Filler, now that you have been shown the problem, do you yourself consider it to be a simple typo or do you need explanation on why this is causing the observed misbehaviour? – Yunnosch Mar 05 '20 at 08:31
  • Some reading need to be shared: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html – Mathieu Mar 05 '20 at 08:36
  • Leave the trailing white space out of `scanf()` format strings (blanks, tabs, and newlines). Usually, if you want a single character input, you should use `" %c"` with a blank _before_ the conversion specification; this skips white space (such as newlines) left over from previous inputs. Most conversions skip white space automatically. Three don't — `%c`, `%[…]` (scan sets), and `%n`. – Jonathan Leffler Mar 05 '20 at 11:18

1 Answers1

1

1)

       scanf ("%s \n",nama);

Here '\n' ignores enter i.e '\n', so can remove '\n' from all scanf

2)

       scanf ("%c",tanya);

Here you must pass by reference not value that is

       scanf ("%c",&tanya);

But in above case you don't need that because

       name==&nama[0]
       pacar==&pacar[0]

EDIT:

if your code is does not ask for character input you can flush input buffer by adding this while loop before scanf().

while ((c = getchar()) != '\n' && c != EOF);
scanf ("%c",&tanya);
srilakshmikanthanp
  • 2,231
  • 1
  • 8
  • 25