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

2020-02-29 20:10发布

问题:

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?

回答1:

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';
}


回答2:

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.



回答3:

You can just simply use isstringstream to convert the string to int as follows

istringstream istringName(intString);
istringName >> real_int_val;

now it has magically become a int containing all numbers from string However I do not see why you would not cin it as a int in the first place??



回答4:

Here is one way to do it

for(int i=0;i<userstr.length();i++){
    myarray[i] = userstr[i];
}