Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / istringstream在读文件时候的应用

用C++从文件里面读取信息的时候,一般用read.getline()函数或者read.read()函数,我们是读取一行的信息。我们读取的这一行信息可能有多个单词,这时候想把每一个单词提取出来,放入到vector<string> vec; 里面去,最简单的方法就是用istringstream来处理。示例代码如下:#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include<sstream>using namespace std;/** 主函数 */
int main()
{
    /** 定义输出输入文件路径 */
    ifstream readFile("d://read.txt");    /** 判断是否能够正确打开文件 */
    if(!readFile)
    {
        cout << "Unable to open myfile" << endl;
        exit(1); // terminate with error
    }    char readLine[256];    vector<string> vec;    while(readFile.read(readLine,256))
    {
        /** 分解每一行的单词 */
        istringstream record(readLine);
        string word;
        while(record >> word)
        {
            vec.push_back(word);
        }        vector<string>::iterator it;
        for(it = vec.begin(); it != vec.end(); it++)
        {
            cout << (*it) << endl;
        }
    }    /** 关闭文件 */
    readFile.close();}本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-03/129217.htm