简体   繁体   English

如何将字符串转换为const char

[英]how to convert string to const char

so i got that first problem working. 所以我遇到了第一个问题。 i run the code and i am prompt to enter some list into the array. 我运行代码,并提示我输入一些列表到数组中。 after entering the list i run this function as a search_func. 输入列表后,我将此功能作为search_func运行。 but it keeps return no record found. 但它一直返回未找到任何记录。 is it because of [0], odd because i have it within a for loop. 是因为[0],还是因为我在for循环中使用它而感到奇怪。

Please help. 请帮忙。 book books[] is a class object.. 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;
}

Try this: 尝试这个:

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

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

EDIT: 编辑:

If gettitle() returns a temporary, then the above method won't work. 如果gettitle()返回一个临时值,则上述方法将不起作用。 You will need to do this instead: 您将需要执行以下操作:

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

I am assuming the first argument is a std::string. 我假设第一个参数是std :: string。 Try calling it's c_str() method. 尝试调用它的c_str()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM