2017-02-02 27 views
-4

即時通訊學習C++的基礎知識。 我想通過C++顯示ANSI表單的.txt文件,但它只顯示25行; 如何顯示100行長的大文本文件?通過C++閱讀和顯示大文本文件

我現在使用的代碼是:

char c[15]; 
ifstream f("file.txt",ios::in); 
f.seekg(0); 
while(!f.eof()) 
{f>>c; 
cout<<c; 
} 
getch(); 
f.close(); 

回答

4

試試這個:

std::string text; 
while (std::getline(f, text)) 
{ 
    std::cout << text << std::endl; 
} 

不要使用字符數組,因爲它們可能會溢出。

在您的代碼中,由於數組的大小,每次讀取限制爲15個字符。

f >> c可能會超出您的數組,因爲您尚未告知系統有多少個字符需要讀取。

Why eof in a loop is bad

+0

我是你的權利,直到['endl'](http://chris-sharpe.blogspot.co.uk/2016/02/why-you-不應該用-stdendl.html)! (另外,'使用namespace std;'?) – BoBTFish

+0

@BoBTFish:我添加了'std ::'前綴。 'endl'是每行刷新緩衝區;一個新手。 –

+2

是的,這就是爲什麼我*不喜歡將它教給新手的原因。太多新手認爲這是流出換行符的唯一「正確」方式。當我在代碼中看到它時,我只能假定它被錯誤地使用了。像這兒。你真的*想要衝洗每一行?如果是這樣,請明確說明它('std :: flush')。 – BoBTFish

1

看讀Why is iostream::eof inside a loop condition considered wrong?

如果必須使用字符數組作爲緩衝區,那麼你應該與它的大小使用std::istream::read。這需要更多的工作才能做到這一點。

你或許應該喜歡:

#include <iostream> 
#include <fstream> 
#include <string> 

int main(){ 
    std::ifstream file("file.txt"); 
    for(std::string line; std::getline(file, line);) 
     std::cout << line << '\n'; 
}