2016-03-04 23 views
-3

我這裏有一些代碼 https://github.com/Fallauthy/Projects/blob/master/cPlusPlusProjects/bazaPracownikow/bazaPracownikow/bazaPracownikow/main.cpp如何顯示文件的內容在C++

而且我不知道如何來顯示我的文件內容。我的意思是我知道如何,但它不顯示相同的我有文件(在鏈接)。它顯示在下一行。此代碼負責加載文件

while (!baseFile.eof()) { 
    //wczytaj zawartosc pliku do zmiennej 
    std::string buffer; 
    baseFile >> buffer; 

    //wypisz 
    loadLineFromBase += buffer; 
    loadLineFromBase += " \n"; 
} 
std::cout << loadLineFromBase << std::endl; 
+4

[*爲什麼'的iostream ::算錯了一個循環條件中eof'?*](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-條件考慮錯誤) – BoBTFish

+0

'baseFile >> buffer'只讀取一個字,而不是一行。使用'getline()'來讀取整行。 – Barmar

回答

0

除非我看到所有的代碼都是我能爲你做的是給你的回報的樣本,我不知道你想做什麼,但它似乎在這種情況下你正在尋找這個。

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

int main() 
{ 

    string Display = ""; 
    ofstream FileOut; 
    ifstream FileInput; 

    FileOut.open("C:\\Example.txt"); 

    FileOut << "This is some example text that will be written to the file!"; 

    FileOut.close(); 

    FileInput.open("C:\\Example.txt"); 

    if (!FileInput) 
    { 
     cout << "Error File not Found: " << endl; 
     return 1; 
    } 

    while (!FileInput.eof()) 
    { 
     getline(FileInput, Display); 
    } 
    FileInput.close(); 
    cout << Display << endl; 

    return 0; 
} 

簡單地說,如果你目前的工作機智公頃文本文檔

使用getline()

當您使用函數getline()需要兩個參數的第一個會在這種情況下你的ifstream的對象,就像你用來打開文件一樣。第二個將是您用來存儲內容的字符串。

使用上面概述的方法,您將能夠讀取整個文件內容。

並請下次如上所述概述您的問題更深入,如果您向我們提供您的所有代碼,我們可能會更好地協助您!

0

您的代碼段會自動爲從輸入文件讀取的每個字符串添加一個換行符,即使最初那些是由空格分隔的單詞。可能你想保留原始文件的結構,所以最好一次讀一行,除非你需要它用於某些其他用途,否則在相同的循環中打印出來。

std::string buffer; 

// read every line of baseFile till EOF 
while (std::getline(baseFile, buffer)) { 

    std::cout << buffer << '\n'; 
} 
相關問題