Home > other >  single character to String conversion
single character to String conversion

Time:02-05

    string exp; //expression
    getline(cin,exp);
    
    stack<int> vs; //value stack (postfix evaluation)
    stack<string> infix; //infix stack (postfix conversion)
    stack<string> prefix; //prefix stack (postfix conversion)
    
        for(int i=0;i<exp.length();i  ){
            char ch = exp[i];
            if(isdigit(ch)){
                vs.push(ch - '0');
                infix.push(string(1,ch));
                prefix.push(string(1,ch));
            }
}

Here I have used string(1,ch) inbuilt constructor to convert single character to a String. But I wanna know, is there any other simple way I can convert single character to string in c ? Like in Java, it can be simply written to convert single character to string is, ch ""

CodePudding user response:

In most cases you can just use {ch}.

std::string s = {ch}; // works
infix.push({ch}); // works

This utilises the std::initializer_list constructor of std::string.

CodePudding user response:

I don't know Java that much, but the closest in C to your ch "" is probably std::string{} ch. Note, that "" is not a std::string, and you cannot overload operators for fundamental types, hence ch "" cannot possibly result in a std::string.

However, std::string{} ch involves 2 strings. I suppose the temporary can be optimized away by the compiler, though to construct a string from one character this is perfectly fine: std::string(1,ch).

For other constructors of std::string I refer you to https://en.cppreference.com/w/cpp/string/basic_string/basic_string.

  •  Tags:  
  • c
  • Related