0

I am using a function that uses a char* parameter; i am reading from a file for input. Here is my code:

std::ifstream infile("file.txt");
std::string line;
while(std::getline(infile,line)){
    if(pass(line.c_str())==0) cout<<"this is correct"<<line<<endl;
}        

the pass function is

int pass(char* a);
//compares c_string to hidden c_string
//if the same then return 0, else retuns -1

I am compiling using g++ -c 6.cpp and the error is:

invalid conversion from 'const char*' to 'char*'

initializing argument 1 of 'int pass(char*)

roalz
  • 2,699
  • 3
  • 25
  • 42

3 Answers3

0

Change to:

int pass(const char* a);
dan
  • 982
  • 8
  • 24
0

When you are converting std::string, c_str() returs a const char* rather than char*, so you must redefine the function to int pass(const char*);.

if you are looking to convert std::string directly to char*,

const char *ptr = str.c_str() ;
char *new_str = new char[str.size()+1];  //+1 for null ending char
strcpy(new_str, str.c_str());

this copies the contents of str into the char* array new_str.

Couchy
  • 753
  • 1
  • 5
  • 25
  • 1
    `strcpy()` stops copying on the first null character. If the `std::string` contains embedded nulls, use `strncpy(new_str, str.c_str(), str.size())` instead, or even `memcpy(new_str, str.c_str(), str.size()+1)` or `std::copy(str.begin(), str.end(), new_str)`. – Remy Lebeau Apr 29 '14 at 00:53
  • `strncpy` also stops on embedded nulls (and even if it didn't, the size should be `str.size()+1`) – M.M Apr 29 '14 at 04:28
0

Call it like this:

if ( !line.empty() && pass(&line[0]) )
     cout << "this is correct" << line <<endl;

You have to check empty as line[0] only works if there is a character in it.

If you are sure that pass does not try to write to the string, you can also go:

pass( const_cast<char *>(line.c_str()) );
M.M
  • 138,810
  • 21
  • 208
  • 365
  • `line[0]` on an empty string is guaranteed to return a reference to a `\0` character. – Quentin Apr 06 '17 at 13:07
  • @Quentin I'm not sure if that was true before C++11 (OP's compilation command shows C++03 mode) – M.M Apr 06 '17 at 19:59
  • A-ha, [not since GCC 6](http://stackoverflow.com/a/33239133/3233393)! Just kidding, [you're right](http://en.cppreference.com/w/cpp/string/basic_string/operator_at), I had forgotten that it wasn't the case in C++03. – Quentin Apr 06 '17 at 20:03