2017-02-21 1 views
-2

ファイルの内容を印刷しようとしていますが、何も印刷されません.0をチェックしてダブルチェックしても見つかりませんそれがうまくいかない理由について何らかの理由があります。ここに私のコードのサンプルがあります。C++プログラムでコンソールにファイルが表示されない

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int main() { 
    ifstream infile("test.txt"); 
    string line; 
    if(infile.is_open()) 
    { 
     cout << infile.rdbuf(); 
    } 
    else 
    { 
     cout << "error" << endl; 
    } 
    infile.close(); 
    return 0; 
} 
+0

バッファに何かを読み込ませることはありませんでしたか? –

+0

私はmain.cppと同じフォルダにファイルを持っています。私は自分のMacBookでxcodeを使用しています。 – science1324

+0

[C++ std :: stringに全体のASCIIファイルを読み込む]の可能な複製(0120-755-002)/ – user4581301

答えて

0

文字列に読み込んで印刷するだけです。

#include <string> 
#include <fstream> 
#include <streambuf> 

void func() 
{ 
    // Read into a buffer. 
    std::ifstream t("file.txt"); 
    std::string str; 

    t.seekg(0, std::ios::end); 
    str.reserve(t.tellg()); 
    t.seekg(0, std::ios::beg); 

    // Assign to a string. 
    str.assign((std::istreambuf_iterator<char>(t)), 
      std::istreambuf_iterator<char>()); 

    // Print out the string to the console. 
    std::cout << str << "\n"; 
} 
+0

ありがとう!しようとしたすべてのファイルは、ファイルを読み込んでコンソールに内容を表示することです。 – science1324

+0

@ science1324投稿が満足できる回答を見つけたら、それをAnsweredとマークしてください。 – DiB

関連する問題