Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to put a string into an integer array c++

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?

like image 744
user3080755 Avatar asked Mar 29 '26 23:03

user3080755


2 Answers

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';
}
like image 174
rami1988 Avatar answered Apr 02 '26 02:04

rami1988


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.

like image 21
Vlad from Moscow Avatar answered Apr 02 '26 02:04

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!