主要使用fstream和数组读取,操作和写入C ++文档 [英] Reading, manipulating, and writing to C++ document using mainly fstream and arrays

查看:533
本文介绍了主要使用fstream和数组读取,操作和写入C ++文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关阅读,操作编写C ++文件流的易于理解和客观指南吗?任何事情在这一点上都是有帮助的。

Is there an easy to understand and objective guide on reading, manipulating writing C++ file streams? Anything would be helpful at this point.

不是有一个简单的,直接的模型,我可以用来读/写/操纵txt文档中的项目列表,包括字符串,整数,双精度,chars和bools?

Isn't there a simple, straight forward model i can use to read/write/manipulate a list of items within a txt document that consists of strings, integers, doubles, chars, and bools?

我可以加载一个文件,读取并转储一个结构化数组(或内存),然后操作结构数组(排序,列表,编辑等) ,然后将其全部转储回文件?

Could I load a file, read and dump everything to a structured array (or memory), then manipulate the structure array (to sort, list, edit, etc.), then dump it all back to the file?

推荐答案

根据不同的格式,您必须以不同的方式阅读。例如,如果您的文件格式为

How if your file formatted? Depending on the format you will have to read it differently. For example if you have a file that has a format like so

John 18
Kelly 19

你可以有一个大致类似的代码来读取它。

you can have a code roughly like so to read it

struct Person{
  string name;
  int age;
}

//create a read operator for Person class
ostream& operator>>(ostream& stream, Person& p){
   return stream >> p.name >> p.age;
}

bool mySortFunc(const Person& p1, const Person& p2){
  return p1.name < p2.name; //sort by name
}

int main(){
  ofstream file('names.txt');
  std::vector<Person> people;
  Person aPerson;
  while( file >> aPerson ){ 
    people.push_back(aPerson);
  }

 //now you have a list of person
 std::sort(people.begin(),people.end(), mySortFunc);

 //do more stuff 
}

上面是编译,它只是给你一个想法。希望它有帮助..

none of the above is compiled, its just there to give you an idea. Hope it helps..

这篇关于主要使用fstream和数组读取,操作和写入C ++文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆