在我的编程课中,我们目前有一个项目要求我们将参数纳入程序。 然后,我需要能够检查其中一个参数,以查看传递给程序的值,以便我可以选择适合该程序的行为。 在之前的家庭作业中,我使用以下代码使用cstring库中包含的strcmp函数执行此操作:
int main(int argc, char *argv[]) { if (strcmp(argv[1], "yes") == 0) { // do this code } else if (strcmp(argv[1], "no") == 0) { // do this code } }但是,出于某种原因,我们不允许在此项目中使用cstring库。 我怎么能这样做?
In my programming class we currently have a project that requires us to take arguments into the program. I then need to be able to check one of the arguments to see which value was passed to the program so that I can choose the appropriate behavior for the program to follow. In a previous homework assignment I did this with the strcmp function included in the cstring library using the following code:
int main(int argc, char *argv[]) { if (strcmp(argv[1], "yes") == 0) { // do this code } else if (strcmp(argv[1], "no") == 0) { // do this code } }However, for some reason we're not allowed to use the cstring library in this project. How else can I do this?
最满意答案
尝试这个:
if (argv[1] == std::string("yes")) { stuff }
如果练习的目的是教授字符串比较如何工作,那么像其他答案建议一样实现for循环。 但是,在C ++中你不应该使用strcmp - 有一个字符串类是有原因的。
Try this:
if (argv[1] == std::string("yes")) { stuff }
If the intent of the exercise is to teach how string comparisons work, then implement a for loop like other answers suggest. However, in C++ you are not supposed to use strcmp - there is a string class for a reason.
更多推荐
发布评论