# Thread: Converting Int Value to a string

1. ## Converting Int Value to a string

Ok my code work, but only to a limit of 10 digits, can someone tell me why it wont work after the 10th digit
I'm making this to emulate a Delphi function call IntToStr.

Code:
```int main(int argc, char *argv[])
{
int number;
cout<<"Enter a number: ";
cin>>number;
cout<<endl;

int x;
int rema, count, digits;

rema = 1;
rema = number;
digits = 0;
while (rema != 0) {
// calculate how many digits int has
rema = rema / 10;
digits++;
}

char numstr[digits];
count = digits - 1;
int left = number;

while (count >= 0) {
// stick the numbers into an array of char startign from then end so they will be in order
numstr[count] =  (left % 10) + '0';
left = left / 10;
count--;
}
string answer = numstr;

system("PAUSE");
return 0;
}```

2. Most likely you're running over the maximum allowed integer for an int, and have some rap-around problems going on. The logic of your algorithm itself seems to be just fine.

Note: The maximum positive value for a signed 32-bit integer is 2,147,483,647 - a 10-digit number.

Cheers

3. thanks. wish it could do better then 10 digits, guess i'll live with it though;

4. No problem. Depending on your compiler, you might have an __int64 type. An unsigned __int64 will give you at least 18 digits.

5. thanks, was thinking about thast. reaidng compiler help files atm
far as i can tell int shouldn't be able to hold anything outside
-32768 to 32767. i shall read on!

6. Try using a long instead.

7. same problem.. perhaps somethign wrong within algorythm

8. On most PCs and such, a short is 16 bits (with range -32768 - 32727), a long is 32 bits (with that ten digit number which happens to be 2^31 - 1 as its range), and an int is one of those two. If you make an integer unsigned, then it can't have any negative values, but twice (plus one) as many positive values.

cout << sizeof(int); will tell you exactly how many bytes you have in an int.

9. int is 4 bytes. i'm doing some recoding to let it us unsigned if its negative. well the number pass if negative is made psoitive but that fact it was negative is stores and added to start of string in the end

10. Hmm unsigned still not helping, can't go over 10. must be something in my code.

11. No... the max unsigned int is still a ten digit number. Your algorithm looks just fine. Try an unsigned __int64. If you're programming in Windows, chances are your compiler will have it.

12. ah thanks. i was still using int.

13. Woohoo it works... now i was stupid when i started this... i'm used to delphi where you cannot output a interger in a string based output, but so far in C++ i havn't had a problem output an int with cout well at least i have this if i need it.

14. can't you just use itoa?

char *buffer[255];

itoa(buffer, 255, myint);

Popular pages Recent additions