如何将字符串中的每个字符转换为ascii值

时间:2014-11-13 00:53:39

标签: c++

我只想将每个字符转换为由x分隔的ascii我希望有65x122x97x45......

之类的内容
#include <iostream>
#include <string>

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

1 个答案:

答案 0 :(得分:0)

这是一个使用stringstreams的解决方案

#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;
}

输出是:

x54x68x69x73x69x73x73x6fx6dx65x74x65x78x74x31x32x33x2ex2ex2e