C++对txt文本进行读写操作

输入输出,是每个程序员的基本功,尤其是对文本的输入和输出。最近,自己在这方面做了一些总结,不是很全面,希望在以后学习和工作的过程中慢慢补充,积累点点滴滴。P.S. 今天天气不错,雾霾散了,天空晴朗,惠风和畅,心情不错。

一、写操作

 

  1. // set.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. #include "string"  
  7. #include "fstream"  
  8.   
  9. using namespace std;  
  10.   
  11. int _tmain(int argc, _TCHAR* argv[])  
  12. {  
  13.     const string data = (string)"hello"+"+"+"world";  
  14.     ofstream out(data,ofstream::app);  
  15.     out << 3 <<endl;  
  16.     out.close();  
  17.     return 0;  
  18. }  

 

 



二、读操作

 

  1. // set.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. #include "string"  
  7. #include "fstream"  
  8. #include "vector"  
  9. #include "sstream"  
  10.   
  11. using namespace std;  
  12.   
  13. struct personalinfo{  
  14.     string name;  
  15.     vector<string> phones;  
  16. };  
  17.   
  18. int _tmain(int argc, _TCHAR* argv[])  
  19. {  
  20.     const string data = "C:\\Users\\helei\\Documents\\Visual Studio 2010\\Projects\\set\\Release\\hello+world";  
  21.     ifstream out(data,ofstream::app);  
  22.     string line,word;  
  23.     vector<personalinfo> people;  
  24.     while (getline(out,line)){  
  25.         personalinfo info;  
  26.         istringstream record(line);  
  27.         record >> info.name;  
  28.         while (record >> word)  
  29.             info.phones.push_back(word);  
  30.         people.push_back(info);  
  31.     }  
  32.   
  33.     cout << people[0].name <<" "<< people[0].phones[0] <<" "<< people[0].phones[1] << endl;  
  34.     cout << people[1].name <<" "<< people[1].phones[0] << endl;  
  35.     cout << people[2].name <<" "<< people[2].phones[0] <<" "<< people[2].phones[1] <<" "<< people[2].phones[2] << endl;  
  36.   
  37.     out.close();  
  38.     return 0;  
  39. }  



 

posted @ 2014-10-27 00:09  spspsp123  阅读(373)  评论(0)    收藏  举报