在C++中,有一个stream这个类,所有的I/O都以这个“流”类为基础的,stream这个类有两个重要的运算符:
1.插入器(<<)
向流输出数据。比如说系统有一个默认的标准输出流(cout),一般情况下就是指的显示器,所以,cout<<"Write Stdout"<<'\n';就表示把字符串"Write Stdout"和换行字符('\n')输出到标准输出流。
2. 析取器(>>)
从流中输入数据。比如说系统有一个默认的标准输入流(cin),一般情况下就是指的键盘,所以,cin>>x;就表示从标准输入流中读取一个指定类型(即变量x的类型)的数据。
在C++编程项目中,代码完成后,往往需要花费大量的时间对写的模块代码进行测试,而测试的case往往不止一两个。模块代码进行更新后,通常还需要进行对所有case进行回归测试。为了能在模块代码修改后,快速地进行回归测试,一般会使用自动化脚本,一次将所有case都执行一遍。
为做到自动化测试的目的,一般情况下,我们可以将每个case的特征信息写在一个文件中,测试时程序读取文件内容并解析出case的特征信息;必要时,我们还需要将程序执行过程中部分结果打印到文件中,以备最后check这个case是否测试通过。
以下是一个实例,为测试一个模块代码,提取case的特征信息有type,地址和id。Stringstream t_ss作为中介,先将getline得到的case文件中的一行 插入到t_ss中,然后再将t_ss 通过析取器解析到各个变量中。直接使用in_stream来析取也可以,但要区分input 文件中的空白行就比较困难。如果input文件中有一个空白行,会导致上一行解析出来的内容打印两次。并且,需要注意,有的时候文件最后一行有空白行,用gvim打开却看不到空白行,这时候可以用vs code打开文件,出现空白行。
结果输出文件为output.csv。csv是一种表格文件,windows下可以用excel打开。输出到表格文件时,列的分隔符是逗号,写完第一行后加上<<endl,接下来将会从第二行第1列开始写。
如果output.csv文件不存在,则新建;如果存在,则覆盖写。如果不想覆盖写,想以追加的方式进行存储到文件中,需要这样打开csv文件out_fstream.open("xxx.csv",ios::app); 其中app是append的意思。
参考 http://www.cplusplus.com/reference/fstream/ofstream/open/
/*
Original 2020-03-21
README:
This is a example to teach you use disjunctor to read a file
which is usefull for testing a module automaticly
execute:
g++ -g -Wall -O0 main.cpp -o sim
*/
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char** argv)
{
std::ifstream in_stream ;
std::ofstream out_stream;
in_stream.open("input.txt");
out_stream.open("output.csv"); //you can open *.csv with windows excel
out_stream<<"type , addr, id" <<endl;// first line in excel
char type;
unsigned int addr;
unsigned int id;
if(in_stream.fail())
{
cout<<"input.txt file is not exist "<<endl;
return 1;
}
while( !in_stream.eof())
{
stringstream t_ss ;
std::string t_string;
std::getline(in_stream, t_string);
t_ss << t_string ;
if(t_string == "\0")
{
cout<<"blank line"<<endl;
continue;
}
t_ss>>type >>std::hex >> addr >> std::dec >> id ;
cout<<" type="<< type << " addr="<<hex<<addr << " id="<<id <<endl;
// add your test function here
// if use in_stream directly, can't distinguish the blank line in input file
// in_stream>>type >>std::hex >> addr >> std::dec >> id ;
out_stream << type <<","<<hex << addr <<","<<id <<endl;
}
return 0;
}