我想知道并理解为什么我的小控制台程序在我运行后就崩溃了,就在一开始,即使它编译成功。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::string> valueWithUnit;
{
std::string unit = '\0';
std::string convertNumb = '\0';
for (double forVal; std::cin >> forVal; ) {
std::cin >> unit;
if (unit != "cm" || unit != "m" || unit != "in" || unit != "ft") {
std::cout << "The unit you entered is not supported by this program.";
std::cout << " Try again with \"cm\", \"m\", \"in\", \"ft\"\n";
}
else {
convertNumb = forVal;
valueWithUnit.push_back(convertNumb + unit);
if (valueWithUnit[valueWithUnit.size() - 1] == "100cm") {
std::cout << "That's also 1 meter.\n";
}
else if (valueWithUnit[valueWithUnit.size() - 1] == "2.54cm") {
std::cout << "That's also 1 inch.\n";
}
else if (valueWithUnit[valueWithUnit.size() - 1] == "1in") {
std::cout << "That's also 2.54 centimeters.\n";
}
else if (valueWithUnit[valueWithUnit.size() - 1] == "1ft") {
std::cout << "That's also 12 inches.\n";
}
}
}
}
for (std::string i : valueWithUnit) {
std::cout << i << std::endl;
}
system("pause");
std::cin.ignore();
std::cin.get();
return 0;
}
当我调试它时,它告诉我:
Unhandled exception at 0x00191644 in Project1.exe: 0xC0000005: Access violation reading location 0x00000000. If there is a handler for this exception, the program may be safely continued.
问题似乎与我的 vector 有关,但我还是不明白。 提前致谢。
最佳答案
if (unit != "cm" || unit != "m" || unit != "in" || unit != "ft") {
如果此 if
表达式的计算结果为真,请注意执行路径不会将新值插入到 valueWithUnit
vector 中。然后……
if (valueWithUnit[valueWithUnit.size() - 1] == "100cm") {
... 如果这是循环的初始、第一次迭代,则 valueWithUnit
vector 仍为空,因为之前的 if
语句跳过了插入valueWithUnit
vector 中的一个值。
因此,valueWithUnit.size() 将在此处返回零。您可以自己解决此错误的其余部分。
关于c++ - 为什么我的小程序刚运行就崩溃了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35110094/