为什么我的小程序在我运行后崩溃了

Why is my little program crashing just after I run it

本文关键字:运行 崩溃 我的 程序 为什么      更新时间:2023-10-16

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

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main() {
    std::vector<std::string> valueWithUnit;
    {
        std::string unit = '';
        std::string convertNumb = '';
        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;
}

当我调试它时,它告诉我:

在 Project1.exe 中0x00191644时未处理的异常:0xC0000005:访问冲突读取位置0x00000000。 如果存在此异常的处理程序,则可以安全地继续该程序。

似乎问题与我的矢量有关,但我仍然不明白。提前谢谢。

if (unit != "cm" || unit != "m" || unit != "in" || unit != "ft") {

如果此if表达式的计算结果为 true,请注意,执行路径不会valueWithUnit向量中插入新值。然后。。。

if (valueWithUnit[valueWithUnit.size() - 1] == "100cm") {

。如果这是循环的初始第一次迭代,则valueWithUnit向量仍将为空,因为前面的 if 语句跳过了将值插入到valueWithUnit向量中。

因此,valueWithUnit.size() 将在此处返回零。您可以自己找出此错误的其余部分。

您正在使用整数常量 0 初始化字符串,这会导致程序在声明 unitconvertNumb 时崩溃。

这是因为整数值 0(即 '' )在传递给需要char const*参数的string构造函数时被视为 nullpointer 值(任何整数常量 0 都可以用作 nullpointer 值)。

std::string unit = '';更改为std::string unit;convertNumb也是如此.

这会将其定义为空字符串。在 c++ 中使用字符串时,不必担心空终止符。