2016-02-04 64 views
3

我正在使用fstream和C++,并且我希望我的程序要做的就是将我的.txt文件的内容打印到终端。这可能很简单,但我在网上看过很多东西,但找不到任何能帮助我的东西。我怎样才能做到这一点?这里是我到目前为止的代码:如何打印出文件的内容? C++文件流

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

int main() { 
    string output; 
    ifstream myfile; 
    ofstream myfile2; 

    string STRING; 
    myfile.open ("/Volumes/LFARLEIGH/Lucas.txt"); 

    myfile2 << "Lucas, It Worked"; 

     myfile >> STRING; 
     cout << STRING << endl; 
    myfile.close(); 


    return 0; 
} 

在此先感谢您。请原谅,如果这是非常简单的,因为我相当新的C++

+0

你得到一个错误 – unicorn2

+0

有COUT << STRING << ENDL – Akshay

+1

您打开相同的文件后两次额外的“}”? – trojanfoe

回答

9

当这个功能已经在标准C++库中实现时,没有理由重新发明轮子。

#include <iostream> 
#include <fstream> 

int main() 
{ 
    std::ifstream f("file.txt"); 

    if (f.is_open()) 
     std::cout << f.rdbuf(); 
}