C++ Pass A String

后端 未结 8 1982
自闭症患者
自闭症患者 2020-12-23 10:51

Quick probably obvious question.

If I have:

void print(string input)
{
  cout << input << endl;
}

How do I call it like

相关标签:
8条回答
  • 2020-12-23 11:28

    Make it so that your function accepts a const std::string& instead of by-value. Not only does this avoid the copy and is therefore always preferable when accepting strings into functions, but it also enables the compiler to construct a temporary std::string from the char[] that you're giving it. :)

    0 讨论(0)
  • 2020-12-23 11:31
    print(string ("Yo!"));
    

    You need to make a (temporary) std::string object out of it.

    0 讨论(0)
  • 2020-12-23 11:40

    Not very technical answer but just letting you know.

    For easy stuff like printing you can define a sort of function in your preprocessors like

    #define print(x) cout << x << endl
    
    0 讨论(0)
  • 2020-12-23 11:42

    You can write your function to take a const std::string&:

    void print(const std::string& input)
    {
        cout << input << endl;
    }
    

    or a const char*:

    void print(const char* input)
    {
        cout << input << endl;
    }
    

    Both ways allow you to call it like this:

    print("Hello World!\n"); // A temporary is made
    std::string someString = //...
    print(someString); // No temporary is made
    

    The second version does require c_str() to be called for std::strings:

    print("Hello World!\n"); // No temporary is made
    std::string someString = //...
    print(someString.c_str()); // No temporary is made
    
    0 讨论(0)
  • Well, std::string is a class, const char * is a pointer. Those are two different things. It's easy to get from string to a pointer (since it typically contains one that it can just return), but for the other way, you need to create an object of type std::string.

    My recommendation: Functions that take constant strings and don't modify them should always take const char * as an argument. That way, they will always work - with string literals as well as with std::string (via an implicit c_str()).

    0 讨论(0)
  • 2020-12-23 11:49

    Just cast it as a const char *. print((const char *)"Yo!") will work fine.

    0 讨论(0)
提交回复
热议问题