2016-04-18 4 views
4

シンプルなコードが抜かれていて、C++ライブラリを使用してプレーンテキストを読み取る方法を学習しようとしています。プログラムと同じディレクトリに、私はtext1.txtにASCIIのプレーンテキストの行が入っています。私は私が代わりにtextOut.txttext1.txtから同じ文字を得るために期待していたコードを実行した後、textOut.txtで私はC++ Seekgは、.txtファイルの実際の文字の代わりに16進アドレスを返すようです。

0x7ffdf21fd018 0x7ffdf21fd018 0x7ffdf21fd018 0x7ffdf21fd018 0x7ffdf21fd018 0x7ffdf21fd018 0x7ffdf21fd018 0x7ffdf21fd018 の100行を持っています0x7ffdf21fd018 0x7ffdf21fd018 0x7ffdf21fd018 0x7ffdf21fd018 0x7ffdf21fd018 0x7ffdf21fd018ここ0x7ffdf21fd018 0x7ffdf21fd018

コードです:

#include <cstdlib> 
#include <stdio.h> 
#include <stdlib.h> 
#include <fstream> 
using namespace std; 

int main() { 

fstream afile; 
afile.open("text1.txt", ios::in); 
ofstream outfile; 
outfile.open("textOut.txt"); 
int counter=0; 
for(counter=0;counter<100;counter++){ 
    outfile << afile.seekg(counter); 
    outfile << "\n"; 
    //printf("%d\n", counter); 
    } 

return 0; 
} 

答えて

0

seekg returns *thisので、<<オペレータがすべてで、この場合に動作することは驚くべきことです。

はむしろ

outfile << static_cast<char>(afile.get()); 

全プログラムを使用します。もちろん

#include <cstdlib> 
#include <stdio.h> 
#include <stdlib.h> 
#include <fstream> 
using namespace std; 

int main() 
{ 

    fstream afile; 
    afile.open("text1.txt",ios::in); 
    ofstream outfile; 
    outfile.open("textOut.txt"); 
    int counter=0; 
    for (counter=0; counter<100; counter++) { 

     afile.seekg(counter); 
     outfile << static_cast<char>(afile.get()); 
     //outfile << afile.seekg(counter); 
     outfile << "\n"; 
     //printf("%d\n", counter); 
    } 

    return 0; 
} 
+0

、目指すは完全に冗長です。 – paddy

関連する問題