Home > Blockchain >  How to check if scanf("%s", &var) is a number, and thus turn it into an integer
How to check if scanf("%s", &var) is a number, and thus turn it into an integer

Time:08-30

I have this code and I need help converting the comments to c code

// if the input of scanf() is "q"
{
   break;
}
else
{
   // convert to int
}

Firstly, how do I check if an input is a certain character. Secondly, how do I turn a string into an integer. Example: "123" -> 123

Things I've tried, that didn't work: (it is possible that I implemented these solutions incorrectly)

CodePudding user response:

I am not using any standard libraries except for stdio.h to print some logging information on the window

you have to know also that any string is terminated by null character which is '\0' to indicate the termination of the string , also you have to check is the user entered characters not numbers and so on (that's not implemented in this code).

I also handled if negative numbers are entered.

but you have to handle if the user entered decimals numbers , to sum up . there are so many cases to handle.

and here the edited code :

#include <stdio.h>

int main(){
    char inputString[100];

    printf("enter the input:\n");
    scanf("%s", &inputString);

    if(inputString[0] == 'q' && inputString[1] == '\0' )
    {
        printf("quiting\n");
        //break;
    }
    else {
        int i = 0;
        int isNegative = 0;
        int number = 0;

        // check if the number is negative
        if (inputString[0] == '-') {
            isNegative = 1;
            i = 1;
        }
        // convert to int
        for ( ;inputString[i] != '\0' ; i  ) {
            number *= 10;
            number  = (inputString[i] - '0');
        }
        if(isNegative == 1)
            number *= -1;

        printf("you entered %d\n", number);
    }
    return 0;
}

CodePudding user response:

You can try this: (Assuming only positive integers needs to convert)

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

int main() {
    // Write C code here
    char var[100];
    int numb_flag=1, i=0,number=0;
    
    scanf("%s",var);
    
    while(var[i]!='\0') { // Checking if the input is number
        if(var[i]>=48 && var[i]<=57)
            i  ;    
        else {
            numb_flag = 0;
            break;
        }
    }
    if(numb_flag==1) {
        number = atoi(var);
        printf("\nNumber: %d",number);
    } else {
        printf("\nNot A Number");
    }
    
    return 0;
}

CodePudding user response:

Here are some guidelines:

  • scanf("%s", &var) is incorrect: you should pass the maximum number of characters to store into the array var and pass the array without the & as it will automatically convert to a pointer to its first element when passed as an argument:

      char var[100];
      if (scanf("           
  •  Tags:  
  • c
  • Related