[英]String to ASCII conversion C++
我有以下代码将std::string
转换为ASCII十六进制输出,代码运行正常,但是有一个小问题。 它不会将空间转换为十六进制。 我该如何解决这个问题。
#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;
}
使用迭代器来代替创建输入流的所有机制:
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;
}
这避免了流输入的复杂性,特别是避免了流提取器( operator>>
)跳过空白的事实。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.