Search code examples
ccharacterscanfletters

Is it possible to ignore certain characters in "scanf_s"?


So here is my code. Its a school assignment. I had to make a program to calculate the square root of a number using a method the Babylonians developed etc, that's not the important part. What I was wondering is if it's possible to ignore letters in my scanf so that when I input a letter it doesn't go berserk in my terminal. Any help is welcome and greatly appreciated.

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

double root_Approach(double s); // defines the two functions 
void ask_Number(void);

int main() {

    ask_Number(); // calls function ask_Number

    printf("\n\n");
    system("pause");
    return 0;
}

double root_Approach(double s) {

    double approach;
    approach = s;
    printf("%.2lf\n", s);       // prints initial value of the number

    while (approach != sqrt(s)) {           // keeps doing iteration of this algorithm until the root is deterimened

        approach = (approach + (s / approach)) * 0.5;

        printf("%lf\n", approach);
    }

    printf("The squareroot of %.2lf is %.2lf\n",s, sqrt(s)); // prints the root using the sqrt command, for double checking purposes

    return approach;
}

void ask_Number(void) {

    double number;

    while (1) {
        printf("Input a number greater than or equal to 0: "); // asks for a number
        scanf_s("%lf", &number); // scans a number

        if (number < 0) {
            printf("That number was less than 0!!!!!!\n");
        }
        else {
            break;
        }
    }
    root_Approach(number);
}

Solution

    1. Scanf reads whatever may be the input from the terminal (character or integer)

    One way you can do is to check the return statement of scanf whether the read input is integer or not an integer.

    Here is the sample code

        int num;
        char term;
        if(scanf("%d%c", &num, &term) != 2 || term != '\n')
            printf("failure\n");
        else
            printf("valid integer followed by enter key\n");
    

    `

    this link may be helpful Check if a value from scanf is a number?