【发布时间】:2015-07-09 16:45:44
【问题描述】:
我正在为课堂作业做作业,我认为我的程序可以正常运行,但现在我想对其进行一些修改,以便更好地理解 assert。代码如下-
#include <iostream>
#include <stdlib.h>
#include <assert.h>
using namespace std;
// Sample program that shows how command line arg works, in Unix g++
// Note argc and argv
// Also shows use of system call, that can launch any program
// system launches 'ls' to display files in the dir
void runAssert(int);
int main(int argc, char *argv[])
{
cout << "Number of inputs: " << argc << endl;
cout << "1st argument: " << argv[0] << endl;
system ("ls");
cout << "hello world" << endl;
runAssert(argc);
return 0;
}
void runAssert(int argc)
{
assert(argc > 4);
}
所以程序应该跟踪通过命令行传递给 main 的参数。教授指定它应该采用 4 个参数。据我所知,此代码有效,但我不知道要传递哪些 4 个命令?我做g++ assignment.cpp -o assignment
然后./assignment -- 但是最后一个命令只算作一个参数,因此断言会触发。如果我将函数更改为>= 1,那么它可以工作。
我的另一个问题是,如何让它在不符合要求时显示错误消息?
我已经尝试过assert("Not the right amount of arguments", argc > 4),但随后我收到一条错误消息,提示传递给 main 的参数过多。
感谢您的帮助,如果我的格式有误,我们深表歉意。第一次发帖。
【问题讨论】:
-
当有人使用错误的方式时,您的程序不应崩溃。
-
澄清克里斯的评论:断言的语义基本上是“如果这个表达式不评估为'true',则程序崩溃” - 你可能不想在这里断言。 cplusplus.com/reference/cassert/assert 或 stackoverflow.com/questions/1571340/…
-
This code works, as far as I can tell, but I don't know what 4 commands to pass it?我们不知道,这是你的程序。您和/或您的教授必须知道该程序的用法。