c++ - 如何将字符串转换为const char

标签 c++ visual-c++

所以我解决了第一个问题。我运行代码,系统提示我在数组中输入一些列表。输入列表后,我将这个函数作为 search_func 运行。但它一直返回未找到记录。是因为 [0] 吗?奇怪的是因为我把它放在 for 循环中。

请帮忙。 book books[]是一个类对象..

int search(book books[], char search) {
    const char* boook =books[0].gettitle();
  //......try this but it failed please help
  cout << "Search books by title:____  ";

  cin >> search;

  bool yes = false;
  int size=2;

  for(int index=0; index<size; index++) {
    if(strcmp(boook,search) == 0 )//....error at this line
         { 
        found = true;
        cout<<"book found "<<endl;
        //cout<<"Author Name: "<<fn<<" "<<ln<<endl;
        break;
      }
  }

  if(!yes)
    cout<<"no book found"<<endl;
}

最佳答案

试试这个:

const char* c_str = books[0].gettitle().c_str();

http://www.cplusplus.com/reference/string/string/c_str/

编辑:

如果gettitle()返回一个临时值,那么上述方法将不起作用。您需要这样做:

string title = books[0].gettitle();
const char* c_str = title.c_str();

关于c++ - 如何将字符串转换为const char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7943014/

相关文章:

c++ - 将 const 添加到指针类型

c++ - VC++ 异常处理 - 应用程序无论如何都会崩溃

c++ - Visual Studio 2012 更新 2 中的 std::async 衰减(丢失)右值引用。任何解决方法?

c++ - VS2015拒绝未命名类型的类内初始化

qt - 程序意外结束

c++ - 如何捕获两个以上的连续信号?

c++ - 使用GraceNote SDK生成Adio指纹

c++ - 使用键盘 Hook 时无法动态退出循环

c++ - 将 SQLite 日期字段转换为 C++ Time_T

C++ 可变说明符