• 课程设计——c++中读取txt文件


    #include <iostream>
    #include <string>
    #include <fstream>
    using namespace std;

    const int Money = 10000;
    struct Patrons
    {
    string name;
    double money;
    };

    int main()
    { ifstream inFile;
    inFile.open("demo6_9.txt");
    if(!inFile.is_open())
    {
    cout<<"could not open the file "demo6_9" ";
    cout<<"program terminating! ";
    exit(EXIT_FAILURE);
    }

    int num;
    inFile>>num;
    cout<<"the number of Patrons is :"<<num<<"."<<endl;
    inFile.get(); .//读取换行符
    // string name;
    // int money;
    Patrons *pt = new Patrons[num];
    if(inFile.is_open())
    {
    int i;
    for(i=0;i<num;i++)
    {
    // inFile>>name;
    // inFile>>money;
    // pt[i].name = name;
    // pt[i].money = money;
    getline(inFile,pt[i].name); //读取一行输入
    (inFile>>pt[i].money).get();
    }

    int k=0;
    cout<<"Grand Patrons:"<<endl;
    for(i=0;i<num;i++)
    if(pt[i].money >= Money)
    {
    cout<<pt[i].name<<" "<<pt[i].money<<endl;
    k++;
    }
    if(k==0)
    cout<<"none. ";

    cout<<"Patrons:"<<endl;
    if(k==num)
    cout<<"none. ";
    else
    {
    for(i=0;i<num;i++)
    if(pt[i].money < Money)
    cout<<pt[i].name<<" "<<pt[i].money<<endl;
    }
    }

    inFile.close();
    delete [] pt;
    system("pause");
    return 0;

    }




    这是我以前做的练习,你看看吧,应该有所帮助~
    我的TXT格式是
    4
    Sam Stone
    2000
    Freida Flass
    100500
    Tammy Tubbs
    5000
    Rich Raptor
    55000
    至于你说的列确定,行不确定,你也可以用类似cin的方法读取~想想你cin怎么用的,ifstream就这么用~
  • 相关阅读:
    LG3626 [APIO2009]会议中心(倍增+树状数组)
    LG3624 [APIO2008]DNA(DP+前缀和)
    CF1516C
    PKUSC2021 口胡题解
    THUSC2021 Day1口胡题解
    2021.4
    2021.3
    2021 暑假 sxyz 集训做题记录
    【做题记录】CF746F Music in Car
    KMP
  • 原文地址:https://www.cnblogs.com/helloaworld/p/5081822.html
Copyright © 2020-2023  润新知