String to int | SoloLearn: Learn to code for FREE!

0

String to int

I wrote this code to convert number string to int and compare:- #include<stdio.h> int str(char S1[],char S2[]) { int x=0,y=0,i; for(i=0;S1[i]!='\0';i++) { x*=10; int m=S1[i]; x+=m; } for(i=0;S2[i]!='\0';i++) { y*=10; int m=S2[i]; y+=m; } if(x>y) return 1; if(y<x) return -1; if(x==y) return 0; } int main() { char S1[100],S2[100]; gets(S1); gets(S2); int a = str(S1,S2); if(a==1) printf("S1 is greater than S2"); else if(a==-1) printf("S2 is greater than S1"); else printf("Both are equal"); return 0; } but x and y are storing garbage values. why is it so? please help.

10/10/2017 12:26:04 PM

Shantanu Shinde

17 Answers

New Answer

+17

If you compare two codes together, you most likely find the answer. In fact, when you are trying to invent the wheel again, weird things might happen!

+16

Here is a workable version of your problem. Notice that GCC compiler no longer supports gets function. [http://cpp.sh/2bbwp] // You can't run it on SL [https://code.sololearn.com/cLnhWQ6YL7x6]

+16

I appreciate that, sir. From now on I'll try my best to reduce those kind of mistakes.

+15

Another way might be using stringstream facilities to do such thing. Here is an ad-hoc solution for an average calculator program . https://code.sololearn.com/cn62B9g73skE/?ref=app

+15

Of course sir. It's probably the worse solution in terms of considering the limits, but at least gives some clue to our friend of how he can reach to a convincing output.

+14

As a clear example, see this fragment. if(x>y) return 1; if(y<x) // is the same sa (x > y) return -1; if(x==y) return 0;

+14

Bookmarked. Thanks again. :)

+2

Well There is a function called atoi and itoa which converts string to integer and integer to string respectively Try that out! Not sure but I think it's in the stdlib header file

+1

so can you pls tell me what wrong with my code?

0

I did that minus of '0' still same thing

0

I don't understand and how is garbage stored in a as well. a takes value from the function and the function returns only 3 values

0

I don't have to use and library func

0

why isn't mine working but?

0

I have done everything same. just I used gets.

0

so what's difference

0

but I have done the same thing. just x>y instead of y<x. so why isn't mine working?