Hello,

I need to take a four digit integer and re-arrange it as follows...

pre: 1234
post: 3412

I have been searching for a method to convert a char array to an int, so I can use the code below. Am I using atoi() incorrectly? The result I get when running the code below is numb = 0.

#include <iostream>
#include <limits>
#include <cmath>
#include <cstdlib>
#include <cstddef>
#include <fstream>
#include <cctype>
#include <ctime>
#include <string>
#include <iomanip>
#include <queue>
#include <stdlib.h>
using namespace std;

int main()
{

	int remainder[4];

	int x = 3241;
	cout << "Number is " << x << endl;
	char num_array[4];
	char hashed_array[4];

	for(int i = 0; i < 4; i++)
	{
		remainder[i] = x % 10;	
		x = x/10;
		
		cout << "Remainder: " << remainder[i] << endl;
		cout << "x: " << x << endl;	
	}

	hashed_array[2] = remainder[3];
	hashed_array[3] = remainder[2];
	hashed_array[0] = remainder[1];
	hashed_array[1] = remainder[0];

	int numb = 4574;
	numb = atoi(hashed_array);
	
	cout << "Hash is " << numb << endl;

}

I figured out how to do it without a char array.

I have another question. When I initialize x to 0123, x prints to the console as 83. Why is this?

#include <iostream>
#include <limits>
#include <cmath>
#include <cstdlib>
#include <cstddef>
#include <fstream>
#include <cctype>
#include <ctime>
#include <string>
#include <iomanip>
#include <queue>
#include <stdlib.h>
using namespace std;

int main()
{

	int remainder[4];
	int hashed_array[4];

	int x = 0123;
	int hashed_x = 0;
	cout << "Number is " << x << endl;

	for(int i = 0; i < 4; i++)
	{
		remainder[i] = x % 10;	
		x = x/10;
		
		cout << "Remainder: " << remainder[i] << endl;
		cout << "x: " << x << endl;	
	}

	hashed_x = remainder[3]*10 + remainder[2] + remainder[1]*1000 + remainder[0]*100;
	
	cout << "Hash is " << hashed_x << endl;

}

I have another question. When I initialize x to 0123, x prints to the console as 83. Why is this?

When you prefix a number with 0, its treated as octal. I think now you can figure out why 83 is getting printed :)

When you prefix a number with 0, its treated as octal. I think now you can figure out why 83 is getting printed :)

Thanks, I did not know that.

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.