c++ 从txt文件读取内容,读取某一行数据

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct game
{
	int num;
	int year;
	float arr[3];
};

struct gj
{
    int a;
    game dz;
};

int count_lines(char *filename) {
    int n = 0;
    ifstream ReadFile;
    string tmp;
    ReadFile.open(filename,ios::in);
    if(ReadFile.fail())
    {
        return 0;
    }
    else
    {
        while (getline(ReadFile, tmp, '\n'))
        {
            n++;
        }
        ReadFile.close();
        cout<<"the rows of txt = " << n<<endl;
        return n;
    }
    

}

int main()
{
    char filename[] = "g1.txt";
    fstream file;
    file.open(filename,ios::in);
    ifstream myfile(filename);
    game g2;
    gj gj1;
    // if(!myfile.is_open())
    // {
    //     cout << "can not open this file" << endl;
    //     return 0;
    // }

    //int row = count_lines("g1.txt");

    if (file.fail())
    {
        cout<< "file not exit"<<endl;
        return 0;
    }

    string s ;
    int line = 4;
    int i = 0;
    // myfile >> gj1.dz.num >>gj1.dz.year >>gj1.dz.arr[0]>>gj1.dz.arr[1]>>gj1.dz.arr[2];
    // cout << "value = " << gj1.dz.year;
    while (getline(myfile,s)&&i < line-2)
    {
        i++;
    }
    myfile >> gj1.dz.num >>gj1.dz.year >>gj1.dz.arr[0]>>gj1.dz.arr[1]>>gj1.dz.arr[2];
    //myfile >> g2.num >> g2.year >> g2.arr[0] >>g2.arr[1]>>g2.arr[2];
    cout << "value = " << gj1.dz.year;
    cout <<" value g2 = " <<gj1.dz.arr[0]<<endl;
    int years = gj1.dz.year;
    cout << years;
    myfile.close();
    return 0;
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值