将字符串转换为const char *

时间:2017-05-15 15:04:09

标签: c++ string char

我有以下代码:

#include <iostream>
#include <windows.h>
#include <mysql.h>
#include <string>
#include <cstring>
using namespace std;

int main()
{
MYSQL* conn;
MYSQL_ROW row;
MYSQL_RES* res;

int qstate; 

conn = mysql_init(0);
if(conn) //if succeeded
    cout << "connection object ok" << endl;
else
    cout << "conn object problem" << mysql_error(conn) <<endl;

conn = mysql_real_connect(conn,"localhost","root","","ascii_table",0,NULL,0);
 if(conn) //if succeeded
 {
   cout << "connection to database ok" << conn << endl;

   string message = "";

    cout << "Enter message:" <<endl;
    getline(cin,message);

    qstate = mysql_query(conn,"select * from datatable");

   if(qstate!=0) //means nonzero
   {

  cout <<mysql_error(conn);
  return 1;
   }
      else{
       res = mysql_store_result(conn);
       const char* c;

     while (row=mysql_fetch_row(res)){
            for(int i=0; i<message.size(); i++){
            string character(1,message[i]);
            c = character.c_str();
            if(c==row[4]){
        cout << "Decimal " << row[0] << "\t";
        cout << "Octal "  << row[1] << "\t";
        cout << "Hexadecimal " << row[2] << "\t";
        cout << "Binary "  << row[3] << "\t";
        cout << "\n";
            }
     }
      }
      }//end else
 }
else{
    cout << "conn object problem" << mysql_error(conn) <<endl;
}
return 0;
}

我的问题现在在这里:

 const char* c;

 while (row=mysql_fetch_row(res)){

        for(int i=0; i<message.size(); i++)
        {
        string character(1,message[i]);
        c = character.c_str();

        if(c==row[4]){
    cout << "Decimal " << row[0] << "\t";
    cout << "Octal "  << row[1] << "\t";
    cout << "Hexadecimal " << row[2] << "\t";
    cout << "Binary "  << row[3] << "\t";
    cout << "\n";
        }
 }
  }

当我运行代码时没有出现错误,但是没有显示十进制,十六进制,八进制和二进制的值。可能是什么问题。我想也许是从字符串转换为const char *但是不是当然。

1 个答案:

答案 0 :(得分:0)

正如Ben Steffan所说,您正在比较指针值而不是内容作为字符串。 您没有传递“if(c == row [4])”,因此您不打印您的值。

在C中有strcmp将char指针比较为字符串: http://www.cplusplus.com/reference/cstring/strcmp/

如果你愿意,你也可以构建字符串对象并进行比较,但效率会降低。