【问题标题】:Can only read one name from text file只能从文本文件中读取一个名称
【发布时间】:2015-02-07 00:30:45
【问题描述】:

我有一个结构 (RECORD),其中包含名称 (char name[25])、年龄 (int age) 和 gpa (float gpa)。我正在尝试从此文本文件中读取数据:

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();

它只读取第一行数据,之后什么也没有。如何让它继续到其余的行?

【问题讨论】:

    标签: file text fstream


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多