只能从文本文件中读取一个名称

时间:2015-02-07 00:30:45

标签: file text fstream

我有一个包含名称(char name [25]),age(int age)和gpa(float gpa)的结构(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++)
{
	f.get(a[i].name, 25); //reads the first 25 characters
	f >> a[i].age >> a[i].gpa;
}
f.close();
&#13;
&#13;
&#13;

它只读取第一行数据,但后面没有。如何让它继续其余部分?

1 个答案:

答案 0 :(得分:1)

我认为这会有所帮助。首先,您需要读取数组中的整个文件并将其转换为字符串数组,其中包含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;
}