Lax_Sam
Lax_Sam

Reputation: 1139

Cs50 greedy without using <cs50.h>

I am solving the greedy algorithm of from the cs50 course without using the cs50 header file. I have written some code. It works fine with numbers as input but when I give it a string or chars as input, it does not prompt me back. I do not know how to solve this issue.

#include <stdio.h>

int main()
{
    float c;
    int C, nQ, rem1, nD, rem2, nN, rem3;

    do
    {
        printf("O hai! How much change is owed? ");
        scanf("%f", &c);
    }
    while(c<0);

    C = c * 100;

    nQ = C / 25;
    rem1 = C % 25;

    nD = rem1 / 10;
    rem2 = rem1 % 10;

    nN = rem2 / 5;
    rem3 = rem2 % 5;

    printf("%d\n", nQ+nD+nN+rem3);
}

Upvotes: 0

Views: 715

Answers (2)

onapte
onapte

Reputation: 267

This is because a float cannot accept a string. You are expecting c to hold other data types when it is just a float variable.

I would suggest you to take input as a string and use atof() to check whether the input is a floating type or not. Something like this:

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

int main()
{
    float c;
    int C, nQ, rem1, nD, rem2, nN, rem3;
    char str[10];

    do
    {
        printf("O hai! How much change is owed? ");
        scanf("%s", str);
    }
    while(atof(str) > 0);
    c = atof(str);
    C = c * 100;

    nQ = C / 25;
    rem1 = C % 25;

    nD = rem1 / 10;
    rem2 = rem1 % 10;

    nN = rem2 / 5;
    rem3 = rem2 % 5;

    printf("%d\n", nQ+nD+nN+rem3);
}

This makes sure that you are using a do while loop only for floating point numbers.

Upvotes: 1

Ajay Brahmakshatriya
Ajay Brahmakshatriya

Reputation: 9203

You are expecting c to be negative after your entered a sequence that is not a floating point number.

This is not a valid assumption. If scanf fails, the value of the variable read is undefined.

You need to check the return value of scanf to know if the read was indeed successful. So you can change the code to.

int read;
do
{
    printf("O hai! How much change is owed? ");
    read = scanf("%f", &c);

    if (read == EOF){
        // Appropriate error message.
        return -1;
    }
    if (read != 1)
        scanf("%*s");
}
while(read != 1 || c < 0);

Now, if the scanf doesn't read a float, it will return 0 and you can continue prompting.

Demo here

Upvotes: 0

Related Questions