内核格式化(C++)

参考《C++ Primer Plus》P788

iostream族支持 程序 与 终端 之间的I/O

fstream族支持 程序 与 文件 之间的I/O

sstream族支持 程序 与 string对象 之间的I/O,也就是说,可以使用cout的ostream方法将格式化信息写入string对象中,并使用istream方法(如getline())来读取string对象中的信息。读取string对象中的格式化信息将格式化信息写入string对象中被称为内核格式化(incore formatting)。

ostringstream

#include <iostream>
#include <sstream>
#include <string>
int main()
{
    using namespace std;
    ostringstream outstr;
    string hdisk;
    cout << "What's the name of your hard disk? ";
    getline(cin, hdisk);  // cin -> hdisk

    int cap;
    cout << "What's its capacity in GB? ";
    cin >> cap;
        
    // write formatted information to string stream   //(格式化信息 -> string对象)
    outstr << "The hard disk " << hdisk << " has a capacity of "
           << cap << " gigabytes.\n";
    string result = outstr.str();
    cout << result;
    
    return 0;
}
    
ostringstream类有一个名为str()的成员函数,该函数返回一个被初始化为缓冲区内容的字符串对象。
string result = outstr.str()
使用str()方法可以“冻结”该对象,这样便不能将信息写入该对象中。




istringstream
#include <iostream>
#include <sstream>
#include <string>

int main()
{
    using namespace std;
    string lit = "It was a dark and stormy day, and "
                 " the full moon glowed brilliantly. ";
    istringstream instr(lit); //use buf for input    lit -> instr
    string word;
    while (instr >> word)  //read a word a time
        cout << word << endl;
    
    return 0;
}
 

istringstream类允许使用istream方法族读取istringstream对象中的数据,istringstream对象可以使用string对象进行初始化。

 

应用

 CMakeLists.txt

cmake_minimum_required( VERSION 2.8 )
project( stream )

# 添加c++ 11标准支持
set( CMAKE_BUILD_TYPE Release )
set( CMAKE_CXX_FLAGS "-std=c++11" )

# 寻找OpenCV库
find_package( OpenCV REQUIRED )
# 添加头文件
include_directories( ${OpenCV_INCLUDE_DIRS} )

add_executable( sstream stringstream.cpp )
# 链接OpenCV库
target_link_libraries( sstream ${OpenCV_LIBS} )

stringstream.cpp

#include <iostream>
#include <fstream>
#include <sstream>


#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;

void readFrame(int index);

int main()
{
    for (int i = 0; i < 3; i++)
    {
        readFrame(i);
    }
    return 0;
}

void readFrame(int index)
{
        string dir = "./data/";
    string rgb = "rgb";
        string dep = "depth";
        string Ext = ".png";

    stringstream ss;
    ss << dir << rgb << index << Ext;  //  ./data/rgb1.png
    string filename;
    ss >> filename;

    Mat color = imread( filename );//rgb
    imshow(filename,color);
        //waitKey(0);
        
    ss.clear();    
    ss << dir << dep << index << Ext;  //   ./data/depth1.png
    filename.clear();
    ss >> filename;

    Mat depth = imread( filename , -1);//depth
    imshow(filename,depth);
        waitKey(0);

    destroyAllWindows();

}

重点是:

ss << dir << rgb << index << Ext;
ss >> filename;


可以将字符串类型(rgb)和整数类型(index)拼起来,index不断更新,可以读取不同下标的文件。
 

猜你喜欢

转载自www.cnblogs.com/112358nizhipeng/p/9256385.html