[英]How to keep reading a file in different functions and not read the file again from the beginning?
[英]Read from the file from different functions
我正在嘗試從另一個函數讀取同一個文件,但它不起作用。 我想問題是我試圖從ifstream &input
讀取,但我不知道實現它的另一種方法
#include <iostream>
#include <fstream>
using namespace std;
class Student{
public:
char name[40]; // i cant use string
int age;
void Input(ifstream &input)
{
input.getline(name, 40);
input >> age;
}
};
void Read(Student *students, int &numberOfStudents)
{
ifstream input("test.txt");
input >> numberOfStudents;
students = new Student[numberOfStudents];
for (int i = 0; i < numberOfStudents; ++i)
students[i].Input(input);
input.close();
}
int main()
{
int size = 0;
Student *students = NULL;
Read(students, size);
for (int i = 0; i < size; ++i)
cout << students[i].name << endl << students[i].age << endl;
return 0;
}
我制作了我的輸入文件
3
1
2
3
4
5
6
(如果程序運行正常,我應該得到 1 - name age - 2 等)但我得到的是沒有年齡 = 1 2 3 的名字
該程序不起作用,因為您定義了:
void Read(Student *students, int &numberOfStudents)
進而
int size = 0;
Student *students = NULL;
Read(students, size);
students
指針是按值傳遞的,因此Read()
不能在函數外更改內存地址。
要解決這個問題,只需通過引用傳遞指針:
void Read(Student *& students, int &numberOfStudents)
最后,正如我所評論的,當使用>>
運算符提取數據時,您需要考慮空格,例如'\\n'
行結尾在文件中:
void Input(ifstream &input)
{
input.getline(name, 40);
input >> age;
input.ignore(1);
}
讀取文件中的學生人數也是如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.