2010-10-09 96 views
0

我剛剛開始使用C++進行編程。我在循環中執行ifstream期間遇到了一些問題。ifstream在循環中不起作用

do 
{ 
    system("cls"); 
    inFile.open ("Account_Details.txt"); 
    while (!inFile.eof()) 
    { 
     getline (inFile, line); 
     cout << line << endl; 
    } 
     inFile.close(); 
     cin.ignore(100, '\n'); 
     cin >> choice; 
} 
while (choice != '1' && choice != '2'); 

這是我的代碼的一部分。循環運行時,它不會在txt文件中顯示數據。
感謝您的幫助。 ^^

+1

適用於我對你沒有顯示的代碼有一些假設,這意味着我的假設是錯誤的。請提供可編譯的完整自包含測試用例。 – zwol 2010-10-09 03:15:09

+4

在C++中執行'while(!file.eof())'幾乎總是一個壞主意。嘗試'while(getline(...)){}'。 – 2010-10-09 03:26:44

+0

那麼,它不打印任何東西? – JoshD 2010-10-09 03:30:32

回答

1

該文件有可能不存在。如果是這樣的話,它會創建一個空文件。檢查文件的路徑。

+0

OP可能使用''中的全局'getline'。 – zwol 2010-10-09 03:17:03

+0

@Zach,啊,是的......那會改變一切。 – JoshD 2010-10-09 03:18:44

+0

Erm ..我的文件第一次執行。但是當選擇不等於1和2時,文件無法打開。如果我使用inFile.getline(line,limit);這是否意味着我將不得不計算我的文件中的字符數? – 2010-10-09 03:19:21

3

加infile.clear()的infile.close後() - 在EOF位不被關閉

+0

+1 ...我被這個咬傷的次數...! – 2010-10-09 18:15:44

0

清除我一直在寫C++代碼了近10年。在那段時間裏,我學會了如何以最小化我創建的錯誤(錯誤)數量的方式使用C++。也許有些人會不同意我的看法,但我會建議你只用於和一邊做循環。永遠不要做。瞭解這兩點,你可以在任何你想要的時間順利循環。

爲了說明我的技術,我冒昧地使用我的風格重寫代碼。它具有完整的錯誤檢查,使用具有預讀while循環,一些C++ 0x中,和簡化流處理:

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

int main(int argc, char** argv) 
{ 
    // check program arguments 
    if (argc<2) { 
     std::cerr << "Usage: " << argv[0] << " file" << std::endl; 
     return EXIT_FAILURE; 
    } 

    // check file can be opened 
    std::ifstream infile(argv[1]); 
    if (!infile) { 
     std::cerr << "Failed to read " << argv[1] << std::endl; 
     return EXIT_FAILURE; 
    } 

    std::string input; 

    // read-ahead 
    std::getline(std::cin, input); 

    while (input!="q" && input!="quit" && input!="exit") { 
     //system("cls"); 

     // print contents of file by streaming its read buffer 
     std::cout << infile.rdbuf(); 

     // read file again 
     infile = std::ifstream(argv[1]); 

     // finally, read again to match read-ahead 
     std::getline(std::cin, input); 
    } 
} 

保存到的main.cpp,編譯成print.exe和運行與print.exe main.cpp。 祝你好運,學習C++!