I have a string that contains what ever the user has input
string userstr = "";
cout << "Please enter a string ";
getline (cin, userstr);
The string is then stored in userstr, I then want the string to be stored in a integer array where each character is a different element in the array. I have created a dynamic array as the following:
int* myarray = new int[sizeof(userstr)];
However how do I then get my string into that array?
You can access each element in your string using the [] operator, which will return a reference to a char. You can then deduct the int value for char '0' and you will get the correct int representation.
for(int i=0;i<userstr.length();i++){
myarray[i] = userstr[i] - '0';
}
int* myarray = new int[ userstr.size() ];
std::copy( usestr.begin(), userstr.end(), myarray );
The terminating zero was not appended to the array. If you need it you should allocate the array having one more element and place the terminating zero yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With