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

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

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

一、写操作

// set.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "iostream"
#include "string"
#include "fstream"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
const string data = (string)"hello"+"+"+"world";
ofstream out(data,ofstream::app);
out << 3 <<endl;
out.close();
return 0;
}


二、读操作

// set.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "iostream"
#include "string"
#include "fstream"
#include "vector"
#include "sstream"

using namespace std;

struct personalinfo{
string name;
vector<string> phones;
};

int _tmain(int argc, _TCHAR* argv[])
{
const string data = "C:\\Users\\helei\\Documents\\Visual Studio 2010\\Projects\\set\\Release\\hello+world";
ifstream out(data,ofstream::app);
string line,word;
vector<personalinfo> people;
while (getline(out,line)){
personalinfo info;
istringstream record(line);
record >> info.name;
while (record >> word)
info.phones.push_back(word);
people.push_back(info);
}

cout << people[0].name <<" "<< people[0].phones[0] <<" "<< people[0].phones[1] << endl;
cout << people[1].name <<" "<< people[1].phones[0] << endl;
cout << people[2].name <<" "<< people[2].phones[0] <<" "<< people[2].phones[1] <<" "<< people[2].phones[2] << endl;

out.close();
return 0;
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: