Reversing a value

I'm reading a list of values from a text file and storing them into a vector. The list of values I read are: 13 21 5 37 15. I'm storing these values in one vector. I want to reverse each individual value so that I can store them in a second vector as: 31 12 5 73 51. I tried using a reversing method but it didn't work.

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
  int main()
{
	int key, value, reverse = 0;
	vector<int> data1;
	vector<int> data2;
	ifstream myFile("p1small.txt", ios::in);
	while (myFile >> key)
	{
		for (unsigned int k = 0; k < TABLE_SIZE; k++)
		{
			value = key;
			int remainder = value % 10;
			reverse = reverse * 10 + remainder;
			value /= 10;
			data2.push_back(value);
		}
		data1.push_back(key);
	}
	myFile.close();
	cout << "Numbers:\n";
	for (unsigned int i = 0; i < data2.size(); i++)
	{
		cout << data2[i] << endl;
	}
}
Last edited on
Let me guess, you're getting something like [3, 31, 310, 2, 21, 210, 5, 50, 500, 7, 73, 730, 5, 51, 510] as your values?

First problem, the for loop in line 9 runs exactly TABLE_SIZE times for each reversal regardless of how many digits you're trying to reverse.

Second problem, you push the value into the array every time you reverse a digit.

Hints:

You're reading the file until the end, when you seem to only want to get a limited number of values.

You should not add values into data2 until they have finished reversing.

You can use a function for reversing the values. This will help ensure that your values get reversed before insertion.

You'll want to loop the reversal of an integer until the integer is equal to 0.
I would recommend converting each number into a string.
This makes it easier to reverse the string. http://www.cplusplus.com/reference/string/string/
After that, you can just use std::stoi() to convert the string back into a number. http://www.cplusplus.com/reference/string/stoi/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
std::string IntToString( const int& num )
{
	std::stringstream ss;
	ss << num;
	return ss.str()
}

std::string ReverseString( const std::string& str )
{
	/*
	have a look at the iterators in the string class
	especially, the reverse iterators
	http://www.cplusplus.com/reference/string/string/string/ (7)
	*/
	return std::string{  }
}

// use std::stoi() to convert the reversed string back into an int 
Last edited on
Topic archived. No new replies allowed.