Tonmoy Mohajan
Tonmoy Mohajan

Reputation: 91

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;
}

Upvotes: 2

Views: 21916

Answers (3)

artless-noise-bye-due2AI
artless-noise-bye-due2AI

Reputation: 22395

Don't use atoi(ar2);. Use strtol(ar2, NULL, 10);

From linux man atoi,

The atoi() function converts the initial portion of the string pointed to by nptr to int. The behavior is the same as

strtol(nptr, NULL, 10);

except that atoi() does not detect errors.

It seems an error in the man page. strtoul() is a better choice for atoi() replicant, but strtol() is a good solution to this question.

See also: atoi() string to int

Upvotes: 0

Bidisha Pyne
Bidisha Pyne

Reputation: 543

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;
}

Upvotes: 1

i486
i486

Reputation: 6563

Before last printf put this line:

if ( atoi( ar ) < 0 ) fnum = -fnum;

Upvotes: 3

Related Questions