【问题标题】:Why did I get error by using strchr() in C++? [duplicate]为什么在 C++ 中使用 strchr() 会出错? [复制]
【发布时间】:2016-08-01 15:30:49
【问题描述】:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main(){
    string a="asdasd";
    if(!strchr(a,'a')) cout<<"yes";
    return 0;
} 

刚开始学习C++编程,不知道为什么会出现这行错误

if(!strchr(a,'a')) cout<<"yes";

但如果我尝试这样编写代码,它会运行得很好。

if(!strchr("asdasd",'a')) cout<<"yes";

我知道这是一个愚蠢的问题,但我真的不知道为什么..对不起..

【问题讨论】:

  • 改用if(!strchr(a.c_str(),'a'))
  • 使用a.find() 而不是strchr
  • 您查看过strchr 的文档吗?
  • 您应该始终向我们展示您遇到的确切错误。此外,您应该停止在 C++ 程序中使用 C 风格的字符串及其相关函数。
  • 哦!谢谢你们,因为我看到其他人使用 strchr,所以我认为它也适用于 C++。

标签: c++ string char strchr


【解决方案1】:

库函数 strchr 用于 C 风格的字符串,而不是 C++ string 类型。

【讨论】:

  • 非常感谢!!!再次抱歉我的愚蠢问题..
【解决方案2】:

使用std::string 时,最接近strchr 的等效项是find

#include <iostream>
#include <string>

int main(){
    std::string a="asdasd";
    if(a.find('a') != std::string::npos) std::cout<<"yes";
} 

【讨论】:

    猜你喜欢
    • 2021-01-12
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多