File tree 1 file changed +6
-4
lines changed
1 file changed +6
-4
lines changed Original file line number Diff line number Diff line change @@ -12,7 +12,8 @@ vector<string> read_lines_from_file(string &file_name) {
12
12
string line;
13
13
14
14
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) {
16
17
getline (file_handle, line);
17
18
lines.push_back (line);
18
19
}
@@ -26,7 +27,8 @@ vector<string> * read_lines_from_file1(string &file_name) {
26
27
string line;
27
28
28
29
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) {
30
32
getline (file_handle, line);
31
33
lines->push_back (line);
32
34
}
@@ -40,7 +42,7 @@ vector<string> * read_lines_from_file1_1(string &file_name) {
40
42
string line;
41
43
42
44
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 ) {
44
46
getline (file_handle, line);
45
47
lines->push_back (line);
46
48
}
@@ -63,4 +65,4 @@ int main() {
63
65
int count1 = read_lines_from_file1_1 (file_name1)->size ();
64
66
cout << " File " << file_name << " contains " << count1 << " lines." ;
65
67
return 0 ;
66
- }
68
+ }
You can’t perform that action at this time.
0 commit comments