我想知道并理解为什么即使刚编译成功,我的小控制台程序在运行后为什么会在一开始就崩溃。
#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;
}
当我调试它时,它告诉我:
似乎问题与我的媒介有关,但我仍然不明白。
提前致谢。
最佳答案
if (unit != "cm" || unit != "m" || unit != "in" || unit != "ft") {
如果此
if
表达式的计算结果为true,请注意执行路径将而不是插入新值到valueWithUnit
vector 中。然后...if (valueWithUnit[valueWithUnit.size() - 1] == "100cm") {
...,如果这是循环的初始迭代,那么
valueWithUnit
vector 仍然为空,因为先前的if
语句跳过了将值插入valueWithUnit
vector 的过程。因此,valueWithUnit.size()将在此处返回零。您可以自己弄清楚该错误的其余部分。