C++从txt文本中输入和读取字符串
来源:互联网 发布:武汉干部网络培训学院 编辑:程序博客网 时间:2024/05/18 01:17
文件的关联
文件操作首先需要包含头文件 fstream。
fstream头文件中定义用于输入的ifstream类和用于输出的ofstream类。
可以通过使用这两个类来声明对象:
ifstream in_file;
ofstream out_file;
将我们声明的对象与文件关联起来:
out_file.open(“name.txt”);
in_file.open(“name.txt”);
Ps:打开的文件最后一定要关闭。例如:out_file.close();
下面的例子包含了向文件输入字符串和从文件读取字符串:
#include <iostream>#include <fstream>#include <cstring>using namespace std;main(){ char filename[20]; //定义文件名字符数组 ofstream out_file; cout << "Enter file name: "; //输入文件名 cin >>filename; out_file.open(filename); //使ouffile关联文件 cout << "Please enter string(q to quit): "<<endl; char str[100]; cin.getline(str,100).get(); //输入文件名 并吸收最后的回车符 while(strcmp(str,"q")!=0) //输入想要输进文件中的字符串 单独输入 q 退出输入。 { out_file << str << endl; // 像使用cout 一样输入到文件中 cin.getline(str,100); } out_file.close(); // 输入完毕 关闭文件 ifstream in_file; in_file.open(filename); string item; getline(in_file,item); //从文件中获取以'\n'为结尾的字符串 while(in_file) { cout <<item <<endl; //输出获取的字符串 getline(in_file,item); } in_file.close(); //输出完毕 关闭文件}
运行结果:
从 apple 一直到 orange 都是输入的字符串 并在输入完成后 按 q 并回车就会退出输入,然后打印出我们输入的字符串。
在上例中使用 getline(in_file,item); 从文件中读取字符串存入item 中。
这一次只从文件中读取:
#include <iostream>#include <fstream>#include <cstring>using namespace std;main(){ char filename[20]; cout << "Enter file name: "; cin >>filename; //输入文件名 ifstream in_file; in_file.open(filename); //关联文件 string item; getline(in_file,item,';'); //从文件中获取以'\n'为结尾的字符串 while(in_file) { cout <<item <<endl; //输出获取的字符串 getline(in_file,item,';'); } in_file.close(); //输出完毕 关闭文件}
运行结果:
在本例中可以看到getline(in_file,item)中加入了’;’ 意思是: ; 号为字符串读取的结尾点。
如果不设置结尾点则像第一个程序一样则会默认为以 \n 字符为结尾点。
通过运行可以看到每次读取时遇到 ; 则停止读取。
可能有人会疑惑在 strawberry 和 mango 之间并没有; 号,那为什么也会换行输出,
而不是像pineapple peach一样连在一起输出呢?
因为当设置了停止符号 ; 号后,'\n' 将不会起作用且会被当作字符存入字符串中。在输出字符串的时候起作用。
- C++从txt文本中输入和读取字符串
- 【C++】从标准输入中读取字符串
- VC++从txt文本中读取字符和数字
- C语言从txt文本中读取多行用逗号分隔的数据
- [C++]读写txt文件和从txt文件中读取数据写入数组中
- java中从文本这种读取字符串
- C 从标准输入读取字符串.
- 分别使用java和C#从读取txt文本
- 读取从a.txt中读取一个字符串,排序后写入b.txt文件中
- C语言从文本文档读取字符串(用户名和密码验证)
- 读取txt文本到一个字符串(java)
- 从txt中读取内容
- VC++中从txt文本中读取数据并且存到二维数组中
- 一种从unicode文本中逐行读取字符串的方法
- C++从纯文本中读取字符串(string)内容
- [object-c]读取txt文本内容
- 如何从输入流中读取数据到字符串中
- Android从assets和raw中读取txt文件
- IOS 数组排序方法
- 非侵入式AOP监控之——AspectJ使用
- 快捷键_MATLAB_模块旋转
- 架构风格
- 实现离线地图行政区域划分
- C++从txt文本中输入和读取字符串
- Android小米(miui)获取通话记录为null解决办法
- 2016/11/23【转载3】USB OTG 引脚定义
- volatile型变量自增操作的隐患
- AndroidIOS风格底部选择器(支持时间,日期,自定义)
- 在线工具使用
- 甲基化RRBS流程:原理+bismark使用
- git常用命令
- 数据仓库