C++ problem. Converting integer into a String based on digits

Apr 23, 2013 at 4:47pm
This problem is really simple.
I want to convert the integer into a string.

1
2
int x = 693; 
char chararr[max];


in my homework, x is unknown. but dont worry, I wont ask for the full code. I just need the part where you change the int into a string/array of char.

I'm thinking in circles from where to start. help?
Apr 23, 2013 at 4:52pm
I recommend you first decide whether you want to convert to a string or an array of char, these are not the same thing. If you want to use a string then you could use stoi(), if your compiler is set to compile to the current standard, C++11.

Apr 23, 2013 at 4:59pm
Oh. ok. array of char. thank you for asnwering, I've been waiting my whole life. T_T
Last edited on Apr 23, 2013 at 4:59pm
Apr 23, 2013 at 5:09pm
Did you try Googling "C convert the integer into a string"?

Apr 23, 2013 at 5:14pm
yes. they all suggest atoi. But I want to learn more about programming, not just functions I hardly know. I was thinking someone here could show me a code for such. something I can really understand and remember in my life.
Apr 24, 2013 at 12:11am
I don't think manually converting from int to an array of chars which would the each digit of the number would be helpful in real life because that's something that the c/c++ compiler takes care for us.

C strings (not C++ string) are handled by an array of chars which are managed by pointers. C++ encapsulates the low level string manipulation, which makes string handling a lot easier. When you declare
string str = "Hello!";

What the compiler basically sees is
char str[] = "Hello!";

Of course, it's more complicated than that but that's the rough idea.

However, if you want to do the reverse, convert from (string) "613" to its int value that is more feasible to do manually.
Apr 24, 2013 at 12:31am
Ok. So you can do exactly what you want with this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int main() {

	unsigned number = 693;

	int digits = floor(log10(abs(number))) + 1;
	cout << number << " has " << digits << " digits" << endl;

	char array[digits];
	unsigned i = digits - 1;
	do {
		 int digit = number % 10;
		 array[i] = 48 + digit
		 number /= 10;
		 i--;
	} while (number > 0);

	cout << "String: " << array << endl;

	return 0;
}


Note: there are support methods to do this with boost or using stringstreams etc. The way I have provided above does it manually :)
Last edited on Apr 24, 2013 at 12:32am
Topic archived. No new replies allowed.