统计代码文本文件的例子 代码来自:http://bbs.csdn.net/topics/390358144 错误代码: #include <iostream> #include <fstream> #include <string> int main() { using namespace std; const char filename[] = "test.cpp"; ifstream fin; string temp; fin.open(filename); if (!fin.is_open()) { cout << "不能打开文件"<< filename << endl; exit(EXIT_FAILURE); } int count = 0; getline(fin, temp); while (fin.good()) { count++; getline(fin, temp); } fin.close(); cout << "文件" << filename << "共有" << count << "行。\n"; return 0; } 错误原因:getline遇到 eof, good函数返回false.所以没有计数,漏计了一行. 正确做法一: int main() { using namespace std; const char filename[] = "c:\\1.txt"; ifstream fin; string temp; fin.open(filename); if (!fin.is_open()) { cout << "不能打开文件"<< filename << endl; exit(EXIT_FAILURE); } int count = 0; while(fin.peek()!=EOF) { count++; getline(fin, temp); cout<<temp<<endl; } fin.close(); cout << "文件" << filename << "共有" << count << "行。\n"; return 0; } 注意不能用fin.eof ,会造成错误. 正确做法2: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { using namespace std; const char filename[] = "test.txt"; ifstream fin; string temp; fin.open(filename); if (!fin.is_open()) { cout << "不能打开文件"<<filename << endl; exit(EXIT_FAILURE); } int count = 0; while (getline(fin, temp)) { count++; cout<<temp<<endl; } fin.close(); cout << "文件" << filename << "共有" << count << "行。\n"; getchar(); return 0; }