Home > Blockchain >  Condition for character in C
Condition for character in C

Time:10-15

I'd like to write a program to convert days into years, weeks, and days. I wrote the program, but there is a condition that if the user inputs a character, the output should be Only positive numeric is allowed. But, when I enter a character, it picks the ASCII value of that. I'm not able to understand what condition to put.

#include<stdio.h>

int main(){
    
    int days, year, weeks;
    printf("Enter days: ");
    scanf("%d", &days);
    
    if(days)
    {
        year = days/365;
        printf("\nYears: %d\n", year);

        weeks = (days-(year*365)) / 7;
        printf("Weeks: %d\n", weeks);
        
        days = days-(year*365)-(weeks*7);
        printf("Days: %d\n", days);
    }
    else{
        printf("Only positive numeric is allowed.");
    }

    return 0;
}

Desired Output:

image

CodePudding user response:

  • Code needs to use the return value of scanf() to determine scanning success.

  • A range test is needed for "positive numbers".


// scanf("%d", &days);
// if(days)
if (scanf("%d", &days) == 1 && days > 0)

  • Related