简体   繁体   中英

String to ASCII conversion C++

I have the following code which converts a std::string to ASCII hex output, the code is running fine but there is one small problem. It is not converting the space to hex. How can I solve that problem.

#include <iostream>
#include <string>
#include <sstream>


int main(){

    std::string text = "This is some text 123...";`

    std::istringstream sin(text);
    std::ostringstream sout;
    char temp;
    while(sin>>temp){
        sout<<"x"<<std::hex<<(int)temp;
    }
    std::string output = sout.str();
    std::cout<<output<<std::endl;
    return 0;
}

operator >> of streams skips white space by default. This means when it hits a space in your string it is just going to skip it and move to the next non white space character. Fortunately there is no reason to even use a stringstream here. We can use just a plain ranged based for loop like

int main()
{
    std::string text = "This is some text 123...";`

    for (auto ch : test)
        cout << "x" << std::hex << static_cast<int>(ch);

    return 0;
}

This will convert every character in the string into a int and then output that out to cout .

Instead of all that mechanism to create an input stream, use iterators:

template <class Iter>
void show_as_hex(Iter first, Iter last) {
    while (first != last) {
        std::cout << 'x' << std::hex << static_cast<int>(*first) << ' ';
        ++first;
    }
    std::cout << '\n';
}

int main() {
    std::string text = "This is some text 123...";
    show_ask_hex(text.begin(), text.end());
    return 0;
}

This avoids the complexity of stream input, and, in particular, the fact that stream extractors ( operator>> ) skip whitespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM