只能从文本文件中读取一个名称
问题描述:
我有一个包含名称(char名称[25]),age(int age)和gpa(float gpa)的struct(RECORD)。我想从这个文本文件中读取数据:只能从文本文件中读取一个名称
Jacqueline Kennedy 33 3.5
Claudia Johnson 25 2.5
Pat Nixon 33 2.7
Rosalyn Carter 26 2.6
Nancy Reagan 19 3.5
Barbara Bush 33 3.4
Hillary Clinton 25 2.5
文件中的每名是25个字符长(即数字是25个字符的权利)。我试图将这些数据复制到RECORD a [7]的数组中。这是我的代码:
fstream f;
f.open("data.txt", ios::in);
for (int i = 0; i < 7; i++)
{
\t f.get(a[i].name, 25); //reads the first 25 characters
\t f >> a[i].age >> a[i].gpa;
}
f.close();
只读取数据的第一线,但没有了。我如何让它继续其余的线?
答
我认为这会有所帮助。首先,您需要读取数组中的整个文件,并将其转换为字符串数组,该数组的长度为25个字符。然后你只需遍历该数组来显示它。
if(f.is_open())
{
//file opened successfully so we are here
cout << "File Opened successfully!!!. Reading data from file into array" << endl;
//this loop run until end of file (eof) does not occ
while(!f.eof() && position < array_size)
{
f.get(array[position]); //reading one character from file to array
position++;
}
array[position-1] = '\0'; //placing character array terminating character
cout << "Displaying Array..." << endl << endl;
//this loop display all the charaters in array till \0
for(int i = 0; array[i] != '\0'; i++)
{
cout << array[i];
/*then you can divide the array in your desired length strings, which here is: Jacqueline Kennedy 33 3.5
Claudia Johnson 25 2.5
Pat Nixon 33 2.7
Rosalyn Carter 26 2.6
Nancy Reagan 19 3.5
Barbara Bush 33 3.4
Hillary Clinton 25 2.5*/
}
}
else //file could not be opened
{
cout << "File could not be opened." << endl;
}