C++中的文件读入
来源:互联网 发布:ddos攻击 linux系统 编辑:程序博客网 时间:2024/06/09 20:09
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//输出空行
void OutPutAnEmptyLine()
{
cout<<"\n";
}
//读取方式: 逐词读取, 词之间用空格区分
//read data from the file, Word By Word
//when used in this manner, we'll get space-delimited bits of text from the file
//but all of the whitespace that separated words (including newlines) was lost.
void ReadDataFromFileWBW()
{
ifstream fin("data.txt");
string s;
while( fin >> s )
{
cout << "Read from file: " << s << endl;
}
}
//读取方式: 逐行读取, 将行读入字符数组, 行之间用回车换行区分
//If we were interested in preserving whitespace,
//we could read the file in Line-By-Line using the I/O getline() function.
void ReadDataFromFileLBLIntoCharArray()
{
ifstream fin("data.txt");
const int LINE_LENGTH = 100;
char str[LINE_LENGTH];
while( fin.getline(str,LINE_LENGTH) )
{
cout << "Read from file: " << str << endl;
}
}
//读取方式: 逐行读取, 将行读入字符串, 行之间用回车换行区分
//If you want to avoid reading into character arrays,
//you can use the C++ string getline() function to read lines into strings
void ReadDataFromFileLBLIntoString()
{
ifstream fin("data.txt");
string s;
while( getline(fin,s) )
{
cout << "Read from file: " << s << endl;
}
}
//带错误检测的读取方式
//Simply evaluating an I/O object in a boolean context will return false
//if any errors have occurred
void ReadDataWithErrChecking()
{
string filename = "data.txt";
ifstream fin( filename.c_str());
if( !fin )
{
cout << "Error opening " << filename << " for input" << endl;
exit(-1);
}
}
int main()
{
ReadDataFromFileWBW(); //逐词读入字符串
OutPutAnEmptyLine(); //输出空行
ReadDataFromFileLBLIntoCharArray(); //逐词读入字符数组
OutPutAnEmptyLine(); //输出空行
ReadDataFromFileLBLIntoString(); //逐词读入字符串
OutPutAnEmptyLine(); //输出空行
ReadDataWithErrChecking(); //带检测的读取
return 0;
}
- C++中的文件读入
- C和C++中的文件读入写出区别
- C和C++中的文件读入写出区别
- 【C/C++】C++读入文件
- c++/c的文件读入和字符串读入总结
- 【C++】将txt文件中的内容读入动态二维数组内
- C++ txt文件中的数据读入数组
- 如何把文件中的数据读入程序
- [C] 从文件读入数据并输出
- 文件读入操作 信息系统 c语言版
- C\C++把TXT文件读入内存
- C语言将文件读入内存
- C++与C的文件读入写入
- C语言:从文件中读入数据
- c 文件读入读出 动态数组
- 深入C语言把文件读入字符串
- 文件读入
- 图片在数据库中的读入与读出 (C#)
- cent os下安装mongodb遇到的问题和解决方法
- android string.xml中格式资源字符串
- 判断表中是否存在记录的SQL语句
- CTime转CString的常用说明
- 笔记《版本控制之道--使用Git》
- C++中的文件读入
- freemark 基础知识
- RHEL5.4配置NFS服务
- MagicISO5.5序列号及如何将dmg 转换为 iso
- Android内存管理策略的优化
- C#生成二维码、调用摄像头扫描二维码
- 【小蒙淘金】如何判断阻力位与支撑位
- WebBrowser的Cookie操作(与CookieContainer的关系)
- 项目1--折腾二维数组