如何将字符串放入整数数组c

如何将字符串放入整数数组c

本文介绍了如何将字符串放入整数数组c ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含用户输入内容的字符串

I have a string that contains what ever the user has input

string userstr = "";
cout << "Please enter a string ";
getline (cin, userstr);

然后将字符串存储在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?

推荐答案

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

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

这篇关于如何将字符串放入整数数组c ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:01