为什么我的小程序在我运行后崩溃了
Why is my little program crashing just after I run it
我想知道并理解为什么我的小控制台程序在我运行它后崩溃,就在一开始,即使它成功编译。
#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 初始化字符串,这会导致程序在声明 unit
和 convertNumb
时崩溃。
这是因为整数值 0(即 ' '
)在传递给需要char const*
参数的string
构造函数时被视为 nullpointer 值(任何整数常量 0 都可以用作 nullpointer 值)。
将std::string unit = ' ';
更改为std::string unit;
。convertNumb
也是如此.
这会将其定义为空字符串。在 c++ 中使用字符串时,不必担心空终止符。
相关文章:
- 在 Ubuntu 服务器上运行 QT 应用程序时崩溃
- 调用 java 的回调() 时应用程序崩溃.由于 detatchThread 而获得运行时错误
- 在传递 com 变体时运行 excel 宏崩溃
- Mac os x app bundle 在下载并运行时崩溃,但在终端或更改 Info.plist 时运行良好
- 如果程序在没有 sudo 的情况下运行,gtk_init会导致 ubuntu 16.04 崩溃
- 当我运行MEX文件时,MATLAB崩溃
- 使用-static libstdc++时std::线程弱,因此在运行时会导致崩溃
- 运行简单的.oct文件时Octave崩溃,我的代码出了什么问题?
- C++具有移动语义的可变参数工厂会导致运行时崩溃
- C++ - 代码在Visual Studio中完美运行,但命令行中的.exe不断崩溃
- 我的视频流程在运行darknet.exe以进行检测对象时崩溃了
- 当使用 /ENTRY:main 和 /MT 运行时库编译为 /SUBSYSTEM:WINDOWS 时,应用程序崩溃
- Omnet++(Eclipse IDE?)在运行INET项目时崩溃 - 在opplibs.dll中EXCEPTION_A
- 使用数组的单向链表:它在运行时崩溃
- "Unable to open file libc++abi.dylib" .程序生成,但在运行时崩溃。使用 xcode 10.1 (10B61)
- 故障转储文件是否需要崩溃时正在运行的本地文件
- 为什么在Shell输出中运行的可执行操作到stdout,而不是崩溃时的stderr
- QT项目在配置文件上崩溃,与发布和调试器一起运行
- 当从共享库运行时,为什么此Android NDK代码崩溃
- 每当我运行注释代码时,程序就会崩溃