ParoX
ParoX

Reputation: 5941

Concatenate character and string literal

My issue is the part:

error_print(argv[0], "invalid option -- '" << (char)optopt << "'");

I know I can't use <<, but I also can't use +. Because it gives error:

error: invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

How can I pass it as a string to my error_print function?

It may seem like over kill but I use it ~20 times, I just made the demo really simple.

PS: I can use C++11.

void error_print(string name, string error) {
    cerr << name << ": " << error << endl << endl;
    cerr << "Usage: " << name << " [-a -b]" << endl;
    exit(1);
}

int main( int argc, char** argv)
{
    bool a_flag = false;
    bool b_flag = false;

    opterr = 0;

    int c;
    while (1) {
        struct option long_options[] =                  
        {
            {"alpha",  no_argument,       0, 'a'}, 
            {"beta",  no_argument,    0, 'b'},
            {0, 0, 0, 0}
        };
        e.
        int option_index = 0;

        c = getopt_long (argc, argv, "ab",long_options, &option_index);

        if (c == -1)
            break;

        switch (c) {
            case 0:
                break;
            case 'a':
                a_flag = true;
                break;
            case 'b':
                b_flag = true;
                break;
            case '?':
                error_print(argv[0], "invalid option -- '" << (char)optopt << "'");
                break;                                              
            default:
                error_print(argv[0], "");
                break;  
        }
    }

Upvotes: 2

Views: 247

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283823

If your compiler is sufficiently new (draft C++14):

"invalid option -- '"s + char(optopt) + "'"s

This feature can be added to C++11 as it has the language support, (the s literal is not provided by the Standard library until C++14)

std::string operator "" s(const char* str, std::size_t len)
{
    return {str,len};
}

Upvotes: 2

Wojtek Surowka
Wojtek Surowka

Reputation: 21003

You cannot use + for literal strings and a single character, but you can use it for std::string, so use

"invalid option -- '" + std::string(1, optopt) + "'"

Upvotes: 3

Related Questions