C++从文件中读入多行数据

C++实现文件读写,可以使用ifstream、ostream来实现
需要包含头文件

#include <fstream>

当创建ofstream对象后,可以把ofstream的对象当做cout一样进行输出。

当创建ifstream对象后,可以把ifstream的对象当做cin一样进行输入。

std::ifstream

来自std::ifstream
在这里插入图片描述
常用的成员函数如下

Public member functions

函数功能
(constructor)Construct object and optionally open file (public member function )
openOpen file (public member function )
is_openCheck if a file is open (public member function )
closeClose file (public member function )
rdbufGet stream buffer (public member function )

Public member functions inherited from istream

函数功能
operator>>Extract formatted input (public member function )
gcountGet character count (public member function )
getGet characters (public member function )
getlineGet line (public member function )
ignoreExtract and discard characters (public member function )
readRead block of data (public member function )
tellgGet position in input sequence (public member function )
seekgSet position in input sequence (public member function )

Public member functions inherited from ios

函数功能
goodCheck whether state of stream is good (public member function )
eofCheck whether eofbit is set (public member function )
failCheck whether either failbit or badbit is set (public member function )
badCheck whether badbit is set (public member function )
operator boolEvaluate stream (public member function )
rdstateGet error state flags (public member function )
setstateSet error state flag (public member function )
clearSet error state flags (public member function )

Public member functions inherited from ios_base

函数功能
flagsGet/set format flags (public member function )
setfSet specific format flags (public member function )
unsetfClear specific format flags (public member function )
  • 构造函数
//默认无参构造
ifstream();
//显式有参构造
explicit ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
explicit ifstream (const string& filename, ios_base::openmode mode = ios_base::in);
//禁止复制构造
ifstream (const ifstream&) = delete;
//移动复制构造
ifstream (ifstream&& x);

关于ios_base::openmode mode的取值,有如下几种:

可取的成员值简述具体含义
in *input打开文件以供读取:内部流缓冲区支持输入操作
outoutput打开供写入的文件:内部流缓冲区支持输出操作
binarybinary二进制模式
ateat end从文件末尾开始输出
appappend所有输出操作都发生在文件的末尾,即在文件现有内容的尾部去添加。
trunctruncate打开之前文件中存在的所有内容都将被丢弃

这个标志可以用或运算(|)来组合

  • 成员函数operator>>
    继承自std::istream
//常见的数值类型,注意这里不支持char&类型,表明不能一次读取一个字符
istream& operator>> (bool& val);
istream& operator>> (short& val);
istream& operator>> (unsigned short& val);
istream& operator>> (int& val);
istream& operator>> (unsigned int& val);
istream& operator>> (long& val);
istream& operator>> (unsigned long& val);
istream& operator>> (long long& val);
istream& operator>> (unsigned long long& val);
istream& operator>> (float& val);
istream& operator>> (double& val);
istream& operator>> (long double& val);
//数组
istream& operator>> (void*& val);

//stream buffers (2)	
istream& operator>> (streambuf* sb );

//manipulators (3)	
istream& operator>> (istream& (*pf)(istream&));
istream& operator>> (ios& (*pf)(ios&));
istream& operator>> (ios_base& (*pf)(ios_base&));

关于operator>>的返回值,
1.返回值为(*this)
2.内部状态错误时,会设置标志位

标志错误
eofbit输入序列中没有更多可用字符(到达文件末尾)。
failbit没有提取任何字符,或者提取的字符不能解释为适当类型的有效值。
badbit流上的错误(例如,当此函数捕获内部操作引发的异常时)。

-成员函数tellg

streampos tellg();

返回当前字符在流中的位置

  • 成员函数seekg
    设置要从输入流中提取的下一个字符的位置。
istream& seekg (streampos pos);
istream& seekg (streamoff off, ios_base::seekdir way);

参数:
pos
相对于流的开始位置的一个绝对位置,整型
off
相对于参数way指定的起点位置的偏移量,有符号的整型

way
为如下三个值,分别表示流的开始位置,当前位置,结尾位置

way可取的值
ios_base::begbeginning of the stream
ios_base::curcurrent position in the stream
ios_base::endend of the stream
  • 成员函数read
istream& read (char* s, streamsize n);

从流中提取n个字符并将它们存储在s指向的数组中。
此函数仅复制数据块,而不检查其内容或在末尾添加’\0’。

如果在成功读取n个字符之前到达文件末尾(即流中字符数量小于n个),则s指向的数组将包含直到该点之前读取的所有字符,并且eofbit和 为流设置了故障位标志。

示例

// read a file into memory
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {
  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    // get length of file:
    //1.设置流中下一次提取字符的位置为流的结尾处
    is.seekg (0, is.end);
    //2.返回当前字符在流中的位置,因为前面将位置设置为了结尾处,
    //所以这里返回的就是流中数据的长度
    int length = is.tellg();
    //3.设置流中下一次提取字符的位置为流的开始处
    is.seekg (0, is.beg);

    // 申请能容纳流中完整数据的动态数组
    char * buffer = new char [length];

    //从流中读取数据
    is.read (buffer,length);
   //关闭文件流
    is.close();

    //将buffer的数据写入标准输出cout
    std::cout.write (buffer,length);
    //释放内存
    delete[] buffer;
  }

  return 0;
}
  • 成员函数operator bool

主要是为了能够根据上下文转换为bool类型,使其能够作为判断条件

explicit operator bool() const;

功能:评估stream
返回值:
false:设置了错误标志(failbit或badbit)
true:没有设置错误标志

std::getline

C++ getline函数用法详解
ifstream的成员函数getline可以用于读取一行字符串,但是需要传入固定大小的字符数组,所以一般不符合我们的需求。

istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

这里可以使用std::getline,std::getline相比于ifstream的成员函数getline最大的优势在于不需要预先确定一行字符串的长度,一行字符串,你想输入多长,就输入多长。

http://www.cplusplus.com/reference/string/string/getline/?kw=getline
头文件

<string>

函数声明

//可以看出getline支持string类作为参数
istream& getline (istream&  is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);

istream& getline (istream&  is, string& str);
istream& getline (istream&& is, string& str);

参数:
is    :表示一个输入流
str   :string类型的引用,用来存储输入流中的流信息。
delim :char类型的变量,所设置的截断字符;在不自定义设置的情况下,遇到’\n’,则终止输入。

利用ifstream和getline从文件中读取多行字符串

// ifstream constructor.
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream
#include <string>       //std::getline
int main () {

  std::ifstream ifs ("test.txt", std::ifstream::in);

  std::string str;
  //每次用输入缓冲ifs中读取一行字符串,
  //遇到文件结束符时,getline返回fasle,跳出循环
   while(std::getline(ifs,str))
       std::cout<<str<<std::endl;

  ifs.close();

  system("pause");
  return 0;
}

在这里插入图片描述

练习题

C++中文件的读取操作,如何读取多行数据

将文件的内容读入到一个vector< string >中,将每一行作为一个独立的元素存于vector中。

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
    ifstream ifs("test.txt");
    if(!ifs) {
        cerr<<"Can't open the file."<<endl;
        return -1;
    }

    string line;
    vector<string> result;
    while(getline(ifs, line))
        result.push_back(line);

    ifs.close();

   for(auto& i:result)
       cout<<i<<endl;

    system("pause");
    return 0;
} 

在这里插入图片描述

C++中文件的读取操作,如何一个一个的读取数据

即将每个单词作为一个独立的元素进行存储

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
    ifstream ifs("test.txt");
    if(!ifs) {
        cerr<<"Can't open the file."<<endl;
        return -1;
    }

    string line;
    vector<string> result;
    while(ifs>>line)
        result.push_back(line);

    ifs.close();

   for(auto& i:result)
       cout<<i<<endl;

    system("pause");
    return 0;
} 

在这里插入图片描述

  • 11
    点赞
  • 90
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值