2017-10-14 48 views
0

嗨我一直在試圖讓我的代碼輸出結果到文本文件沒有任何運氣。如果有人能幫我看一下,我將非常感激。 我試圖fstreamcout沒有任何運氣...最終我只是用批次file.exe > Out.txt出來的結果。無論如何,在cpp代碼中這樣做不會把頭髮拉出來?十六進制數組cout到文本文件失敗

這是我應該輸出的當前代碼...我做錯了什麼?

#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

使用['std :: hex'](http://en.cppreference.com/w/cpp/io/manip/hex)掃描書寫的I/O操縱器有什麼問題? – user0042

回答

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();