Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ cannot convert 'const char*' to 'std::string*'

Tags:

c++

string

stl

I have this code below and I'm getting the error upon compilation:

error: cannot convert 'const char*' to 'std::string*' for argument '1' to 'void sillyFunction(std::string*, int)'

#include <iostream>
#include <string>

using namespace std;
int counter = 0;

void sillyFunction(string * str, int cool=0);

int main(){
    sillyFunction("Cool");
    sillyFunction("Cooler", 1);
    return 0;
}

void sillyFunction(string * str, int cool){
    counter++;
    if (cool){
        for (int i=0; i<counter; i++) cout << *str << endl;
    } else {
        cout << *str << endl;
    }
}
like image 281
Pwnna Avatar asked May 13 '11 13:05

Pwnna


2 Answers

Don't take your parameter in as a string * try just using a const string & instead

EDIT:

std::string and const char* are different types. the std::string already has a conversion from string literals (ex: "Cool") to the actual string object. So by passing in the string literal "Cool" you are in a sense passing in a std::string object, not a pointer to one.

The reason I chose to use a const string & is mostly from personal coding practices. This minimizes stack memory usage, and since you are passing in a constant string literal, there is no need for the parameter to be modify-able.

Also don't forget if you change from a string * that you no longer need to dereference it in your cout:

if (cool){
    for (int i=0; i<counter; i++) cout << str << endl;
} else {
    cout << str << endl;
}
like image 180
Dan F Avatar answered Sep 18 '22 20:09

Dan F


change

void sillyFunction(string * str, int cool){
   counter++;
    if (cool){
        for (int i=0; i<counter; i++) cout << *str << endl;
    } else {
        cout << *str << endl;
    }
}

to

void sillyFunction(const char* str, int cool){
    counter++;
    if (cool){
        for (int i=0; i<counter; i++) cout << str << endl;
    } else {
        cout << str << endl;
    }
}
like image 34
Sam Miller Avatar answered Sep 18 '22 20:09

Sam Miller