c++ - 如果我不给它提供命令行参数,为什么我的程序会崩溃?

标签 c++ command-line crash command-line-arguments

我制作了一个简单的测试程序来使用 C++11 线程。

#include <iostream>
#include <stdlib.h>
#include <thread>
using namespace std;

void tee(int civ)
{
    for(int loop=0; loop<19; loop++, civ++)
    {
        civ = civ%19;
        cout << loop << "\t" << civ << endl;
        this_thread::sleep_for(chrono::milliseconds(300));
    }
}

void koot()
{
    while(true)
    {
        cout << ":) ";
        this_thread::sleep_for(chrono::milliseconds(300));
    }
}

int main(int argc, char *argv[])
{
    thread saie(tee, atoi(argv[1])),
        kamaa(koot);
    saie.join();
    kamaa.join();

    return 0;
}

只要我提供命令行参数,它就可以正常工作,但如果不提供,它就会崩溃。 如何解决这个问题? 我尝试检查参数计数,如果它们存在,则无济于事。

编辑:我必须添加这一行:

if(argc < 2) return 1;

最佳答案

由于您正在访问而崩溃

argv[1]

如果有的话,它将保存一个命令行参数(程序名称除外)。您应该检查argc是否大于1。为什么大于1?因为第一个命令行参数是程序本身的名称。所以argc总是大于0。索引从 0 开始。因此,如果 argc == 1,则只有 argv[0] 有效。

#include <iostream>
int main(int argc, char* argv[])
{
  // no need to check argc for argv[0]
  std::cout << argc << " " << argv[0] << "\n";
}

关于c++ - 如果我不给它提供命令行参数,为什么我的程序会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14404626/

相关文章:

android - 当我在android中来电时启动Activity时应用程序崩溃

c++ - 卡住了,需要帮助从 vector 列表返回时间跨度

c++ - 比较 argv 和 L"test"不工作

c++ - 为什么样本不是随机填充我的 vector ?

c - 打印出当前工作目录

ios - TestFlight TFLog 异常使我的应用程序崩溃

使用 mujoco-py 包的 MuJoCo 物理库的 Python 绑定(bind)

unit-testing - 如何从命令行运行单元测试?

regex - 如何 : Searching for a string in a file from the Windows command line?

android - VelocityTracker 在 Android 4.4 上导致崩溃