繁体   English   中英

字符串到ASCII的转换C ++

[英]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;
}

流的operator >>默认情况下会跳过空格。 这意味着当它在字符串中命中空格时,将跳过它并移至下一个非空格字符。 幸运的是,这里甚至没有理由使用stringstream 我们可以仅使用基于范围的普通for循环

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

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

    return 0;
}

这将每个字符转换为字符串成int输出,然后说出来cout

使用迭代器来代替创建输入流的所有机制:

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.

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