0
嗨我一直在試圖讓我的代碼輸出結果到文本文件沒有任何運氣。如果有人能幫我看一下,我將非常感激。 我試圖fstream
和cout
沒有任何運氣...最終我只是用批次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++解碼器
使用['std :: hex'](http://en.cppreference.com/w/cpp/io/manip/hex)掃描書寫的I/O操縱器有什麼問題? – user0042