C++ strings and arrays (very simple)
I am having an extremely difficult time trying to solve this. I would like to know how can I store a string input into an array in C++? I would like the array to be of size 12 because the inputs are going to be binary numbers, so for example this is what I want:
The input开发者_JAVA技巧 is going to be a binary number, 10100 for example, and I want to store that binary number into an array so that the array will look like this --> [1][0][1][0][0]
. I want to store in an array any binary number, or, any number of 0's and 1's that the user gives.
the simplest solution is to use the c_str() function of c++ string. This will create a null terminated array of characters that's the same as your original string (you can just ignore the last byte)
so if you have the string myString
char * byteArray = myString.c_str()
will produce the above array
keep in mind that you can also just reference strings using []
string myString = "1101"
//option 1
char firstBit = myString[0];
//option 2
const char * primitiveArray = myString.c_str();
char firstBitOther = primitiveArray[0];
精彩评论