0
#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;
}
3
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by Narue
0

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";
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.