#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();
#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所定义的变量