清除我一直在寫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++!
適用於我對你沒有顯示的代碼有一些假設,這意味着我的假設是錯誤的。請提供可編譯的完整自包含測試用例。 – zwol 2010-10-09 03:15:09
在C++中執行'while(!file.eof())'幾乎總是一個壞主意。嘗試'while(getline(...)){}'。 – 2010-10-09 03:26:44
那麼,它不打印任何東西? – JoshD 2010-10-09 03:30:32