C++_文本文件读写常用代码
来源:互联网 发布:php中连接符 编辑:程序博客网 时间:2024/06/06 06:39
数据测试:有一个文件file.txt,内容入下:
- This life will always love you.
- Let me always love you!
- If you have locked in my memory, and that the key to keeping your life on it for me.
说明:省略了一些判断,如文件打开失败
1、逐词读入,放到字符串中,逐词处理
- #include <iostream>
- #include <fstream>
- #include <string>
- using namespace std;
- void main()
- {
- ifstream file("file.txt");
- string word;
- while (file>>word) // >>:读取成功,返回true,读取失败返回false
- {
- cout<<word<<endl;
- }
- system("pause");
- }
运行结果:见一个单词换一行。
This
life
......
for
me.
2、逐行输入,并放到字符数组中,逐行处理
- #include <iostream>
- #include <fstream>
- using namespace std;
- void main()
- {
- const int len=100;
- char str[len];
- ifstream file("file.txt");
- while (file.getline(str,len))//len表示这次输入字符串的最大值,getline读取成功,返回true,读取失败返回false
- {
- cout<<str<<endl;
- }
- system("pause");
- }
运行结果:见一句换一行
This life will always love you.---第一次循环
Let me always love you! ---第二次循环
If you have locked in my memory, and that the key to keeping your life on it for me. ---第三次循环
注意:
1)这个getline函数是 ifstream流 的成员函数
2)如果一行中的数据长度超过len,就会读取失败,返回false
3)第一个参数是 指针类型*,不能使用string类型
3、 逐行输入,存放字符串中,逐行处理
- #include <iostream>
- #include <fstream>
- #include <string>
- using namespace std;
- void main()
- {
- string str;
- ifstream file("file.txt");
- while(getline(file,str)) //getline:读取成功,返回true,读取失败返回false
- {
- cout<<str<<endl;
- }
- system("pause");
- }
注意:这个getline函数是 string 头文件中提供的一个函数,与上一个例子不同,使用要加头文件#include <string>
运行结果:见一句换一行
This life will always love you.---第一次循环
Let me always love you! ---第二次循环
If you have locked in my memory, and that the key to keeping your life on it for me. ---第三次循环
注意:>>从文件读入内存时,见到空格、Tab、回车 会停止接受
file.getline():一行为单位,见到回车停止,但是见空格、Tab不停止
- C++_文本文件读写常用代码
- C++_文本文件读写常用代码
- C++_文本文件读写常用代码
- C#文本文件读写代码
- 读写文本文件(C#)
- Objective-c 读写文本文件
- c/c++读写文本文件
- Objective-c 读写文本文件
- 常用的C/C++文本文件的读写函数
- C#_文件读写常用类介绍
- Android读写Txt文本文件代码
- C#:读写简单的文本文件
- c#winform文本文件的读写
- C/C++读写文本文件、二进制文件
- C++_文件读写
- C++_文件读写
- javascript读写TEXT文本文件示例代码
- c:文本文件的读写(simple版)
- 软件开发人员的出路
- 矩阵练习
- MJParallaxCollectionView 视差滑动效果
- sort()函数与qsort()函数及其头文件
- 支付宝集成
- C++_文本文件读写常用代码
- Spice 客户端GTK版本,安装依赖环境
- zoj 3802 Easy 2048 Again (14.8 浙大月赛 E)
- c++ 局部对象指针及到底是在堆上创建的对象还是在栈上创建的?
- 通过修改apache改变域名指向
- 71道经典Android面试题和答案--重要知识点都涉及到了
- 关于一些Android课程资料
- UVA 1471 - Defense Lines(扫描+二分)
- [SPOJ ORDERSET] Order statistic set [Treap]