Search code examples
catoi

How do I get a negative value by using atoi()?


I wrote this code to get a number in reverse form. But if I use any negative input it shows positive reversed number. Can the atoi function in C handle negatives?

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

int main(void) {
  char ar[40];
  char ar2[40];
  int fnum;
  scanf("%s", ar);

  for (int i = strlen(ar) - 1, j = 0; i >= 0; i--) {
    ar2[j] = ar[i];
    j++;
  }

  fnum = atoi(ar2);
  printf("%d", fnum);
  return 0;
}

Solution

  • You can use strstr(haystack, needle) to convert it to negative number.

    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    
    int main(void){
    char ar[40];
    char ar2[40];
    int fnum;
    scanf("%s",ar);
    for(int i=strlen(ar)-1,j=0;i>=0;i--){
        ar2[j]=ar[i];
        j++;
    }
    if(strstr(ar, "-"))
        fnum= - atoi(ar2);
    else
        fnum= atoi(ar2);
    printf("%d",fnum);
    return 0;
    }