Convert to char

Is there a way to convert and substr index of a str to char?
I haven't compiled this yet, so there might be error. But, you can see I'm trying to convert a substr index into a char so I can use it in a switch statement.

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
26
27
28
29
30
31
#include <iostream>
#include <string>

int main() 
{
	std::string biNum = "00000111";
	char cChar;
	int temp = 0;

	for(int i = 0; i < 8; i++)
	{
		cChar = static_cast<char>(biNum.substr(i, 1));

		while(temp >= 0 || cChar == '1')
		{
			switch(cChar)
			{
			case '0':
				temp = temp * 2;
				break;
			case '1':
				temp = (temp * 2) + 1;
				break;
			default:
				std::cout << "Sorry, only 0s and 1s.";
				break;
			}
		}
	}
	return 0;
}
Last edited on
You can do this:

cChar = biNum.substr(i, 1)[0]

That works assuming the substring has at least one character in it.

Of course you can always do this in the first place:

1
2
3
4
for(int i = 0; i < 8; i++)
{
    cChar = biNum.at(i);
    ...
Last edited on
(Side note: you can use a string in the same manner as a character array, just use the [ ] brackets like you where working with a character array)

this code should work in any program you throw at it as long as you tell the compiler what mystring is.

1
2
3
4
5
6
7
8
string mystring;
int slength;
/*code to set the contents of 'mystring' */
slength = mystring.length();
char mychar[slength];
for(int a = 0; a <= slength; a++){
         mychar[a] = slength[a];
}


this will take every character in the string into the array, including spaces from the space bar, but again, for most uses(don't hold me to it, I could be wrong) just use a string as if it were an array and it will do what you want it to do.

EDIT: this will make the character array the exact length of the string and won't quit the for loop till it copies all the characters. and make sure you include the string header. #include<string>
Last edited on
Topic archived. No new replies allowed.