Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

single character to String conversion

    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 + ""

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading