c++ - 如何在此代码中正确使用 strcmp() ?

标签 c++ string strcmp

我想比较 cs[i][a].days[x]"Mon" 以确定我是否可以将此字符串放入星期一的目录... 但是好像不行? (无匹配函数)

#include <iostream>
  #include <string>
  #include <cstring>
    struct course{
        string name;
        string *days; //dynamic array of days int start_hr, start_min;
        int start_hr, start_min;
        int end_hr, end_min;
    };
            void print_day2(course **cs,int num, int number, int day){
                    cout << "Monday: " << endl;
                    for(int i = 0; i <number; i++){
                        for(int a = 0; a < num;a++){
                            for(int x = 0; x < day; x++){
                                if(strcmp(cs[i][a].days[x], "Mon")==0){
                                    cout << cs[i][a].days[x] <<endl;
                                }
                            }
                        }
                    }

最佳答案

虽然很想调用 ->c_str() 来使用 strcmp 进行 C 风格比较,但最好只使用 ->compare( ) 或简单地 == 因为它们是更原生的 C++ 习语

C 风格(不推荐):

strcmp (cs[i][a].days[x].c_str(), "Mon")

成员函数:

cs[i][a].days[x].compare("Mon")

关系运算符

cs[i][a].days[x] == "Mon"

请注意,这不会将 "Mon" 转换为 string,因为 ->compare()== 覆盖了 const char *

关于c++ - 如何在此代码中正确使用 strcmp() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34124577/

相关文章:

java - 为什么打印者将我的信息分成两个字符串?

c - 以下程序中用于字符串比较的段错误

c++ - ffmpeg 在多线程中解码 JPEG 2000

c++ - Clang 跳过初始化列表构造的处理

c++ - 在 C++ 中使用适当的数据类型(路径、字符串等)和 boost::filesystem 来高效地迭代文件、更改文件名和执行文件操作

c# - 如何使用 C# 将带反斜杠的字符串插入到表中

objective-c - 将字符串与 Objective-C 中的数组进行比较

c++ - C++ 的新运算符是可重入的(或异步安全的)吗?

比较两个字符串,strcmp 的问题

c - strcmp 总是产生相同的结果