2017-10-14 1 views
0

안녕하세요, 행운을 빌지 않고 결과를 텍스트 파일에 출력하려고했습니다. 누군가 나를 위해 그것을 볼 수 있다면 크게 감사하겠습니다. 행운없이 fstreamcout을 사용해 보았습니다 ... 결과적으로 나는 결국 file.exe > Out.txt 배치를 사용했습니다. 어쨌든 내 머리카락을 꺼내지 않고도 cpp 코드에서이 작업을 수행 할 수 있습니까?16 진수 배열 Cout to text file failure

이것은 출력해야하는 현재 코드입니다 ... 내가 뭘 잘못하고 있니?

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