My final exam is two hours away, please help..

Jan 16, 2012 at 1:43am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
using namespace std;
char* int2str(int a)
{
	int i=0;
	char s[100];
	while(a/10!=0){
		s[i]=(char)(a%10);
		a=a/10;
		i++;
	}
	return s;
}

void main()
{
	int a;
	cout<<"Enter a: ";
	cin>>a;
	char*p=int2str(a);
	cout<<*p;
}


I am supposed to convert an integer into a string. I don't see why this code is not working, please help..
Jan 16, 2012 at 2:02am
You need to tell us what's not working about it.
Jan 16, 2012 at 2:11am
s is allocated inside the function and will not exist after the function has returned, so in main() you get a dangling pointer. There are several ways to solve this. One way is to dynamic allocate the array char* s = new char[100];[100];

The while loop condition should probably be while(a != 0) because otherwise you ignore the last digit.

line 8 is also not correct. The char '0' is not the same as the int 0. You just need to add the value of '0' to the digit value to make it correct: s[i] = '0' + (a%10);


When you print the string on line 21 you should remove the * or otherwise you will only print the first char in the string.
Jan 16, 2012 at 2:18am
Well, without knowing what the problem is, I can't tell you much. What is the point of (a%10)?
Jan 16, 2012 at 2:29am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
using namespace std;
char* int2str(int a)
{
	char *s= new char[100];
	int i=0;
	while(a!=0){
		s[i]=(a%10)+'0';
		a=a/10;
		i++;
	}
	return s;
}

void main()
{
	int a;
	cout<<"Enter a: ";
	cin>>a;
	char* answer=int2str(a);
	cout<<answer;
}




i modified according to you peter, the program is still not working properly.

If i enter integer a as 123, it would return 321 followed by random symbols. I just don't get it?!
Jan 16, 2012 at 3:08am
The random characters are because you are not null terminating the string which is needed for knowing when the string ends. s[i] = '\0'; after the loop should fix it.

The digits are in the reverse order. You can either come up with a way to add the digits in the opposite order or reverse the final string.
Jan 16, 2012 at 3:16am
Thank you so much!.

Exam's in 45 minutes, wish me luck!!..

Object oriented next semester hehehe.
Topic archived. No new replies allowed.