在没有cstring的情况下比较C ++中的字符数组和字符串文字(Comparing character arrays and string literals in C++ without cstri

编程入门 行业动态 更新时间:2024-10-22 07:16:42
在没有cstring的情况下比较C ++中的字符数组和字符串文字(Comparing character arrays and string literals in C++ without cstring)

在我的编程课中,我们目前有一个项目要求我们将参数纳入程序。 然后,我需要能够检查其中一个参数,以查看传递给程序的值,以便我可以选择适合该程序的行为。 在之前的家庭作业中,我使用以下代码使用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.

更多推荐

本文发布于:2023-04-27 23:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329685.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   字符   情况下   文字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!