2

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;
}
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Tonmoy Mohajan
  • 91
  • 2
  • 4
  • 13
  • 2
    Unrelated to your question, but where do you terminate `ar2`? Remember that `char` strings are really called ***null-terminated** byte strings*. – Some programmer dude Jun 02 '17 at 13:36
  • As for your question, in a string containing a negative number, where is the minus character? After reversing, where will the minus character be? – Some programmer dude Jun 02 '17 at 13:38
  • 2
    Your loop is backwards. If you enter in a positive number, it will also be printed in reverse. Is this intentional? Negative numbers will show as positive because the `-` occurs at the end of the string and is not treated as part of the number. – Michael Mior Jun 02 '17 at 13:38
  • because if you enter "-12345" you convert it to "54321-". You need to check if the 1st character is a dash. – OldProgrammer Jun 02 '17 at 13:38
  • You have to copy minus sign from last to first position. Otheriwse `atoi` cannot return negative value. – i486 Jun 02 '17 at 13:38
  • [don't use `atoi`](https://stackoverflow.com/q/17710018/995714) – phuclv Jun 02 '17 at 13:42
  • How can you read your own code, the formatting and indentation is truly awful. Please learn about this, it's important or no one will ever enjoy reading your code. – user9993 Jun 02 '17 at 14:20
  • The _null character_ is not set in `ar2[]`, so `atoi(ar2);` is UB. – chux - Reinstate Monica Jun 02 '17 at 16:13

3 Answers3

3

Before last printf put this line:

if ( atoi( ar ) < 0 ) fnum = -fnum;
i486
  • 6,491
  • 4
  • 24
  • 41
1

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;
}
Bidisha Pyne
  • 543
  • 2
  • 13
0

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

artless noise
  • 21,212
  • 6
  • 68
  • 105