Skip to content

Commit 03ee450

Browse files
authored
Update c++_example1.cpp
1 parent 92dd0fe commit 03ee450

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

codingStyleIdioms/3_RAII/c++_example1.cpp

+6-4
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ vector<string> read_lines_from_file(string &file_name) {
1212
string line;
1313

1414
ifstream file_handle (file_name.c_str());
15-
while (file_handle.good() && !file_handle.eof()) {
15+
// file_handle.peek()!=EOF 解决多读一行问题
16+
while (file_handle.good() && !file_handle.eof() && file_handle.peek()!=EOF) {
1617
getline(file_handle, line);
1718
lines.push_back(line);
1819
}
@@ -26,7 +27,8 @@ vector<string> * read_lines_from_file1(string &file_name) {
2627
string line;
2728

2829
ifstream file_handle (file_name.c_str());
29-
while (file_handle.good() && !file_handle.eof()) {
30+
// file_handle.peek()!=EOF
31+
while (file_handle.good() && !file_handle.eof() && file_handle.peek()!=EOF) {
3032
getline(file_handle, line);
3133
lines->push_back(line);
3234
}
@@ -40,7 +42,7 @@ vector<string> * read_lines_from_file1_1(string &file_name) {
4042
string line;
4143

4244
ifstream file_handle (file_name.c_str());
43-
while (file_handle.good() && !file_handle.eof()) {
45+
while (file_handle.good() && !file_handle.eof() && file_handle.peek()!=EOF) {
4446
getline(file_handle, line);
4547
lines->push_back(line);
4648
}
@@ -63,4 +65,4 @@ int main() {
6365
int count1 = read_lines_from_file1_1(file_name1)->size();
6466
cout << "File " << file_name << " contains " << count1 << " lines.";
6567
return 0;
66-
}
68+
}

0 commit comments

Comments
 (0)