一、从文件中读取数据ifstream>>
//功能:把文件中的数据读到变量的值中 #include<fstream> #include <string> #include <iostream> using namespace std; int main() { int i=0; int count = 0; //文件中 string m_name , m_passwd; ifstream file_read; //定义读取文件的对象 file_read.open("name.txt"); //打开存放用户名和密码的文件 if(!file_read) { cout<<"打开文件失败"<<endl; } else { while(!file_read.eof()) //用此方法会多循环一次 { file_read>>m_name>>m_passwd; //一行一行 cout<<m_name<<" "<<m_passwd<<endl; i++; } count = i; //因为多循环一次,所以i的初始值是0 file_read.close(); } }二、往文件中写入数据ofstream<<
//功能:把变量的值写入到文件中 //将数组m_name、m_passwd、sex中的数据写入文件中 #include<fstream> #include <string> #include <iostream> using namespace std; int main() { int i=0; int count = 5; //文件中 string m_name[5] = {"AA","BB","CC","DD","EE"}; string m_passwd[5] = {"1","2","3","4","5"}; string sex[5] = {"M","M","W","W","M"}; ofstream file_write; file_write.open("name.txt"); if(!file_write) { cout<<"打开文件失败"<<endl; } for(i=0;i<count;i++) //注意:空格、endl都可以写入文件中去 file_write<<m_name[i]<<" "<<m_passwd[i]<<" "<<sex[i]<<endl; }