c++ - 为什么我的小程序刚运行就崩溃了

标签 c++ debugging crash

我想知道并理解为什么我的小控制台程序在我运行后就崩溃了,就在一开始,即使它编译成功。

#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/

相关文章:

java - 在另一个链接/使用 .so 文件

c++ - wxWidgets: wxString::wxString(int) 在此上下文中私有(private)

android - 在 Android 应用程序中处理 "Don' t 保留 Activity

c++ - 在 C++ 中打印所有小于 n 的素数(文件崩溃)

c++ - Meson 选择了错误的编译器(GCC 而不是 clang)

c++ - pselect() 与循环中的 accept()

.net - 为什么 .NET 应用程序会阻止 Windows 关闭?

android - 启用 Android 支持库调试标志的最佳方式

java - 如何检测 Swing 线程策略违规

java - 从静态方法崩溃调用非静态方法