【发布时间】:2019-09-09 11:54:32
【问题描述】:
我是一位经验丰富的 Python 程序员,正在尝试学习 C++。我在初始化固定大小的整数数组时遇到问题。
我已阅读this,但将我的整数创建为常量并没有解决我的问题。我在这里错过了什么?
顺便说一句,我正在使用 VS2019 社区,任何帮助将不胜感激!
#include <iostream>
#include <sstream>
int numericStringLength(int input) {
int length = 1;
if (input > 0) {
// we count how many times it can be divided by 10:
// (how many times we can cut off the last digit until we end up with 0)
for (length = 0; input > 0; length++) {
input = input / 10;
}
}
return length;
}
int convertNumericStringtoInt(std::string numericString) {
std::stringstream data(numericString);
int convertedData = 0;
data >> convertedData;
return convertedData;
}
int main() {
std::string numericString;
std::cout << "Enter the string: ";
std::cin >> numericString;
const int length = numericStringLength(convertNumericStringtoInt(numericString));
std::cout << "Length of Numeric string: " << length << "\n";
int storage[length];
}
【问题讨论】:
-
你可以使用
std::array<int, size_you_want_ie_20> my_array。 -
使用
std::vector<int>,除非你有充分的理由不这样做。 -
@nada 问题是在编译时不知道大小,这是
std::array所必需的。 -
@Shawn 有答案时使用答案部分
-
你也一样@nada