Need help turning a string to an int

Sep 20, 2015 at 3:47am
How would I go about turning a nice character string into three separate int values so I can sum there ascii values of each set?

For example "ABCDEFGHI"
- "ABC"
- "DEF"
- "GHI"

Sep 20, 2015 at 4:57am
Several ways. You could separate each of them into their single translated integer values, while storing each of nine letters into a separate declared variable.

Or I would probably create a character array/vector for every set of 3, and for each array/vector, go through its elements and add them up respectively.

Btw are you asking to get the size of each ascii? Or are you trying to determine their binary or hex value as defined in C++?
Sep 20, 2015 at 5:18am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main()
{
	std::string str = "Helle World!";

	unsigned sum = 0;

	for (auto &it : str)
	{
		sum += static_cast<int>(it);
	}

	std::cout << "Sum: " << sum << '\n';

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

	return 0;
}


If you don't have a C++11 supported compiler just replace the for loop parameters with a normal iterator based on the string length.
Last edited on Sep 20, 2015 at 5:20am
Topic archived. No new replies allowed.