Why does the program quit before scanf

1

I have the following code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    float a, b, c, delt, c0, c1, c2;
    char s;
    int op = 1;

    printf("Welcome.\n\n");
    while (op == 1) {
        printf("Please type: a, b c.\n\n");

        printf("a:");
        scanf("%f",&a);
        printf("b:");
        scanf("%f",&b);
        printf("c:");
        scanf("%f",&c);

        delt = b*b;
        printf("%c \n",delt);

        printf("Do you want repeat? (y/n)");
        scanf("%c",&s);

        if (s != "y") {
            op = 0;
        }

    }
    return 0;
}

Why does the last scanf() not wait for input to continue with if and decide if the process can be terminated?

I'm using the GNU C compiler if it's useful.

    
asked by anonymous 25.03.2017 / 22:56

2 answers

4

Double quotes instead of simple quotes.

  

if (s! = "and" ) {      op = 0;   }

Do this:

  

if (s! = 'and' ) {      op = 0;   }

When you want to read a character you can always use getchar() that is specifically made for this type of case.

I suggest that you change the %c where you print the value of del to %.2f or simply %f because it reads numbers of data type float , real. For the rest, in the part where you read the value of s to avoid capturing the value in buffer and invalidating the entry of y / n you can proceed as in the @Lucas Tuesday response. p>

  • double: (string)
  • simple: (char)

To declare variables of type bool , simply import the library, or you can define it manually using any of these examples.

#include <stdbool.h>

#define bool int
#define true 1
#define false 0 

typedef enum {true, false} bool;

#import <boolean.h> // já obsoleto nalguns compiladores

Then you can use bool var normally.

    
25.03.2017 / 23:18
2

There is an error in your program that Edilson commented on, but it does not solve the problem of early termination. You must add a space to your scanf to ignore the line break (and any space) that was generated before pressing ENTER . Here's how:

printf("Do you want repeat? (y/n)");
    scanf(" %c",&s);

Note the white space before %c .

Modify too:

printf("%c \n",delt);

by

printf("%f \n",delt);

Because delt is of type float.

    
25.03.2017 / 23:24