上机必备——文件输入输出

复试上机常用文件输入输出方法

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

/*
	先将如下信息写入文件中:
		01 李江 男 21
		02 刘唐 男 23
		03 张军 男 19
		04 王娜 女 19
	然后输入学号查询学生信息 
*/
int main(){
    
    
	string fname = "f:\\bit\\student_info.txt";
	//in out是以控制台为主体来看的,从控制台输出数据则是out,输入数据则是in 
	ofstream out(fname.c_str());//这种形式不行:"f:\\bit\\student_info.txt".data() 
	string str;
	while(getline(cin, str)){
    
    
		if(str == "end"){
    
    
			break;
		}
		out<<str<<endl;
	}
	string directive, info;
	bool flag = false; 
	while(cin>>directive){
    
    
		if(directive == "00"){
    
    
			break;
		}
		flag = false;
		ifstream in(fname.data());//每次查询都要打开一次文件,是为了保证in指向文件的开头,从而保证下面循环的进行 
		while(!in.eof()){
    
    
			getline(in, info);//若使用in>>info则遇到空格则结束 
			//若字符串为字符数组类型,in.getline(ch, length); 
			//若知道格式,也可这样输入:in>>no>>name>>sex>>age; 
			if(info.find(directive) != string::npos){
    
    
				flag = true; 
				cout<<info<<endl;
			}
		}
		if(in.eof() && flag == false){
    
    
			cout<<"查无此人!"<<endl;;
		}
		in.close();
	}
} 

猜你喜欢

转载自blog.csdn.net/baidu_36004106/article/details/105126942