convert string to int array?

Hi, I'm grabbing an 8 bit integer from a file using an ifstream object and assigning it to a string.

Example, I'm grabbing 10101010 from a file and assigning it to stringName.

1
2
3
ifstream inFile;
string = stringName;
inFile >> stringName;


the problem is, I MUST convert stringName to an int array, where arrayName[0]=1, arrayName[1]=0, arrayName[2]=1 etc.

Can anyone PLEASE show me code how to do this? Its for a project, and I want to figure the rest out myself, but this one step is holding me up.

For any numeric digit you can get the actual value by subtracting out the ascii value of '0'

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cstring>

int main()
{
  char charArray[] = "10101010";
  int intArray[strlen(charArray)];
  for(int idx = 0; idx < strlen(charArray); idx++)
  {
    intArray[idx] = charArray[idx] - '0';
  }
}
Ok, I understand that, but the "10101010" is stored as a string, not a char array. What's the syntax to convert a string to a char array so I can use the above?

1
2
3
4
#include <algorithm>

std::transform( stringName.begin(), stringName.end(), array,
                []( char c ) -> int { return ( c - '\0' ); } ); 
Last edited on
error C2039: 'transfer' : is not a member of 'std'

is the error I get when I try to use the above....
a "string" is just a specialized character array with a null terminator. (with the exception of std::string)
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;

int main(){
	const int SIZE = 8;
	string test = "10101010";
	int buffer[SIZE];

	for(int i = 0; i < SIZE; i++){
		buffer[i] = test[i]-48;
	}

	for(int i = 0; i < SIZE; i++){
		cout << buffer[i];
	}

	system("pause");
	return 0;
}


I believe this will do it, because my bits will always be 8. Not sure why the -48 works, but I guess it has something to do with ASCII
@enosmac
error C2039: 'transfer' : is not a member of 'std'

is the error I get when I try to use the above....


There was a typo. Instead of transfer shall be transform.


@enosmac
Not sure why the -48 works


48 is ASCII code of '0'. It is better to use '0' instead of 48.
Last edited on
Topic archived. No new replies allowed.