#include<iostream.h>
#include<string.h>
int main()
{
	int x;
	cout<<endl<<"enter x:";
	cin>>x;
	int temp=x;
	int count=0;
	while(temp!=0)
	{
		count++;
		temp=temp/10;
	}
	char *p=new char[count+1];
	for(int i=0;i<count;i++)
	{
		*(p+i)='\0';
	}
	for(i=count-1;i>=0&&x!=0;i--)
	{
		*(p+i)=x%10;
		x=x/10;
	}
	*(p+count)='\0';
	cout<<endl<<"converted string : ";
	for(i=0;i<count;i++)
		cout<<(int)*(p+i); // int type cast used , if not used then integers are not printed in cout
						   //is there an alternative method ?
	return 0;
}

Recommended Answers

All 2 Replies

there are several ways to convert a string of digits to an integer. One of them is by using c++ stringstream class, which is based on fstream but works on strings instead of files

#include <string>
#include <sstream>

int main()
{
    char digits[] = "1234";
    int x = 0;
    stringstream stream(digits);
    stream >> x;

    cout << x << "\n";
}

And converting from int to strring is just as simple

#include <string>
#include <sstream>

int main()
{
     int x = 12345;
    string digits;
    stringstream stream;
    stream << x;
    stream >> digits;
    cout << digits << "\n";
}

Your code doesn't properly handle negative values, amitahlawat20.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.