如何将字符串放入整数数组 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20458881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:09:45  来源:igfitidea点击:

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

c++arraysstringintegerint

提问by user3080755

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:

然后将该字符串存储在 userstr 中,然后我希望将该字符串存储在一个整数数组中,其中每个字符都是数组中的不同元素。我创建了一个动态数组,如下所示:

int* myarray = new int[sizeof(userstr)]; 

However how do I then get my string into that array?

但是,我如何将我的字符串放入该数组中?

回答by rami1988

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.

您可以使用 [] 运算符访问字符串中的每个元素,该运算符将返回对字符的引用。然后您可以扣除 char '0' 的 int 值,您将获得正确的 int 表示。

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

回答by Vlad from Moscow

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.

终止零未附加到数组。如果您需要它,您应该为数组分配一个多元素并自己放置终止零。

回答by Fred Roy

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

您可以简单地使用 isstringstream 将字符串转换为 int,如下所示

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??

现在它神奇地变成了一个包含字符串中所有数字的 int 但是我不明白你为什么不把它作为一个 int 放在首位?

回答by prole92

Here is one way to do it

这是一种方法

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