如何修复cpp随机崩溃

问题描述 投票:0回答:1

我编写的这个 C++ 程序在运行时不断崩溃。

#include <iostream>

using namespace std;

void compile_program() {
    cout << "worked";
    string *cppfile;
    string *outputfile;

    cout << "FILENAME: ";
    cin >> *cppfile;
    cout << endl << "OUTPUT FILE: ";
    cin >> *outputfile;
    cout << endl;

    string command = "g++ " + *cppfile + " -o " + *outputfile;

    system(command.c_str());
}

int main() {
    while (true) {
        cout << "Welcome to the program loader." << endl;
        cout << "OPTION 1: Compile program" << endl;
        cout << "OPTION 2: Run program" << endl;
        cout << "> ";
        char *opt;
        cin >> opt;
        cout << endl;
        if (opt == "1" || opt == "a" || opt == "A") {
            compile_program();
        } else if (opt == "2" || opt == "b" || opt == "B") {
            // run_program();
        }
    }
}

当我给它一个选项后,它就只是等待...... ...然后崩溃。

有什么帮助吗?

c++ runtime-error runtime
1个回答
0
投票
  1. 您正在尝试取消引用未初始化的指针,例如:

cin >> *cppfile;

cin >> *输出文件;

要解决此问题,请将这些变量的类型更改为“std::string”对象,并使用“std::cin”直接为其赋值。

  1. 将 opt 从“char*”更改为“char”类型。
  2. 将比较中的双引号与“opt”替换为单引号:

if (opt == "1" || opt == "a" || opt == "A")

if (opt == '1' || opt == 'a' || opt == 'A')

  1. 包含字符串库以确保程序正常运行:

#include“字符串”

© www.soinside.com 2019 - 2024. All rights reserved.