Hex Array cout到文本文件失败

时间:2017-10-14 09:10:40

标签: c++ windows file printf

您好我一直试图让我的代码将结果输出到文本文件而没有任何运气。如果有人能为我看一下,我会非常感激。 我试了fstreamcout没有任何运气......最后我只是使用批file.exe > Out.txt来输出结果。无论如何在cpp代码中执行此操作而不拔我的头发?

这是我应该输出的当前代码......我做错了什么?

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <fstream>

int hex_to_int(char c)
{
    if (c >= 97)
        c = c - 32;
    int first = c / 16 - 3;
    int second = c % 16;
    int result = first * 10 + second;
    if (result > 9) result--;
    return result;
}

int hex_to_ascii(char c, char d){
        int high = hex_to_int(c) * 16;
        int low = hex_to_int(d);
        return high+low;
}

int main(){

   std::string line,text;
   std::ifstream in("Input.txt");
   while(std::getline(in, line))
   {
       text += line ;
   }
        const char* st = text.c_str();
        int length = strlen(st);
        int i;
        char buf = 0;
        for(i = 0; i < length; i++){
                if(i % 2 != 0){


                std::ofstream out("Output.txt");
                std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
                std::cout.rdbuf(out.rdbuf()); //redirect std::cout to Output.txt CrickeyMoses!
                printf("%c", hex_to_ascii(buf, st[i]));
                std::cout << std::flush;
                std::cout.rdbuf(coutbuf);
                }else{
                        buf = st[i];                          
                }
        }
}

INPUT.TXT:

2b524553503a4754494e462c3046303130362c3836323139333032303637373338312c2c34312c38393135343530303030303030343333353631322c33312c302c312c302c2c342e312c302c302c2c2c32303137313031323231353932332c2c2c2c30302c30302c2b303030302c302c32303137313031323232303032322c3534344324
0A
2b524553503a4754494e462c3046303130362c3836323139333032303637373338312c2c34312c38393135343530303030303030343333353631322c33312c302c312c302c2c342e312c302c302c2c2c32303137313031323231353932332c2c2c2c30302c30302c2b303030302c302c32303137313031323232303032322c3534344324

Output.txt的:

+RESP:GTINF,0F0106,862193020677381,,41,89154500000004335612,31,0,1,0,,4.1,0,0,,,20171012215923,,,,00,00,+0000,0,20171012220022,544C$
+RESP:GTINF,0F0106,862193020677381,,41,89154500000004335612,31,0,1,0,,4.1,0,0,,,20171012215923,,,,00,00,+0000,0,20171012220022,544C$

十六进制到ASCII C ++解码器

1 个答案:

答案 0 :(得分:3)

不要再重定向std::cout。您似乎想要执行此操作,以便将返回值格式化为printf的字符。这可以通过将其转换为char然后直接输出到std::ofstream来完成。

std::ofstream out("Output.txt", std::ios::out);

for (i = 0; i < length; i++){
    if (i % 2 != 0){
        out << static_cast<char>(hex_to_ascii(buf, st[i]));
    } else {
        buf = st[i];
    }
}

out.close();