【发布时间】:2019-02-20 03:37:58
【问题描述】:
我试图制作一个程序来获取用户的整数输入,然后将该 int 中的每个单个数字过滤为偶数和奇数。写完代码没有任何错误,但运行时出现错误。
我的代码:
#include <iostream>
#include <string>
#include <array>
#include <stdio.h>
#include <cstring>
#include <sstream>
using namespace std;
int main() {
int input = NULL;
int EvenNumbering = 0;
int OddNumbering = 0;
cout << "Please input a number: ";
cin >> input;
string str = to_string(input); //Convert it to string
char cstr[str.length];
int EvenNo[str.length];
int OddNo[str.length];
strcpy(cstr , str.c_str()); //Put it into char array
//Now filter Even number and Odd number
for (string x : cstr) {
int z = stoi(x);
if (z % 2 == 0) {
EvenNo[EvenNumbering] += z;
EvenNumbering++;
}
else {
OddNo[OddNumbering] += z;
OddNumbering++;
}
}
cout << endl;
cout << "Even Numbers: ";
for (int x : EvenNo) {
cout << x << ", ";
}
cout << endl;
cout << "Odd Numbers: ";
for (int x : OddNo) {
cout << x << ", ";
}
system("pause");
return 0;
}
我的错误:
source.cpp(18): error C2131: expression did not evaluate to a constant
source.cpp(18): note: a non-constant (sub-)expression was encountered
source.cpp(19): error C2131: expression did not evaluate to a constant
source.cpp(19): note: a non-constant (sub-)expression was encountered
source.cpp(20): error C2131: expression did not evaluate to a constant
source.cpp(20): note: a non-constant (sub-)expression was encountered
source.cpp(26): error C2065: 'x': undeclared identifier
source.cpp(40): error C2065: 'x': undeclared identifier
source.cpp(47): error C2065: 'x': undeclared identifier
1>Done building project "Question.vcxproj" -- FAILED.
对 C++ 还是新手,这是我的第一个项目,所以如果我犯了一些初学者的错误,请原谅我。
【问题讨论】:
-
尝试使用
std::vector而不是 C 风格的数组。 (int name[size]) 它将为您节省很多问题。 -
char cstr[str.length];-- 这不是合法的 C++。如果您想要一个动态数组,请使用std::vector<char>。此外,您使用的编译器会出现此错误,这是一件好事。太多的 C++ 新手使用允许这种语法的编译器品牌,因此他们最终认为自己编写的代码是有效的 C++。 -
还有,为什么要使用
cstr之类的char数组呢?只要坚持所有字符数据都是std::string。那么你就不需要不必要的strcpy了。 -
char cstr[str.length]、int EvenNo[str.length];和int OddNo[str.length];被称为“可变长度数组”(VLA)。它是一个 GCC 扩展。您需要找到 MSVC 等价物。您应该考虑改用std::vector。