您的位置:首页 > 编程语言 > C语言/C++

C++文件流操作,从文件中读取数据并显示

2013-04-17 18:24 477 查看
#include <iostream>

#include <iomanip>

#include <fstream>

#include <cstdlib>

#include <string>

using namespace std;

int main()

{

    ifstream inFile;

    inFile.open("get.txt");

    if(!inFile.is_open()){

        cout << "Can't open the File" << endl;

        exit(0);

    }

    int age[7];

    int count = 0;

    string name[7];
    string s_name;

    while(!inFile.eof()){

        getline(inFile,s_name);

        if(s_name[0] == '\0'){

            cout << "读取到换行符" << endl;

        }

        cout<<"Read one line:"<<s_name<<endl;

        inFile >> age[count];

        inFile >> name[count];

        ++count;

    }

    for(count = 0 ; count < 7 ; count ++){

        cout << age[count] << endl;

        cout << name[count] << endl;

    }

    inFile.close();
}

//代码分析

//红色部分为为了区分getline函数与cin的区别,而加的额外的代码

//由于get.txt文件中有多行,所以我定义了数组形式

首先引入fstream头文件

其次定义ifstream变量(注意和ofstream的区别)

然后便可以像使用cin一样使用ifstream所定义的变量
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐