CVS格式数据解析例子,使用std::quoted这个东西。
#include <iostream>
#include <iomanip>
#include <sstream>
void construct_cvs_formated_stream( std::stringstream& ss)
{
std::string row1 = R"NOTPRINTFLAG("12", "Chaoyang Qu, Jianguomen Dajie")NOTPRINTFLAG";
std::string row2 = R"NOTPRINTFLAG("10", "He said,""Hello."", and run ...")NOTPRINTFLAG";
ss << row1 << "\r\n";
ss << row2 << "\r\n";
}
int main()
{
std::stringstream cvs_data;
construct_cvs_formated_stream(cvs_data);
std::string line;
while (std::getline(cvs_data, line)) {
std::stringstream row;
row << line;
std::string id;
row >> std::quoted(id);
std::string tmp;
std::getline(row, tmp, ',');
std::string content;
row >> std::quoted(content,'"','"');
std::cout << id << " " << content << std::endl;
}
return 0;
}
VS2015有个bug,out << quoted()调用时, 当delim和escape字符都是双引号"时,出现bug。
其它新一些的编译器正常。
生成CVS格式的例子如下:
void construct_cvs_formated_stream( std::stringstream& ss)
{
const char delim = '"';
const char escap = '"';
ss << std::quoted("12")<<","<<std::quoted("Chaoyang Qu, Jianguomen Dajie")<<"\r\n";
ss << std::quoted("10")<<","<<std::quoted("He said,\"Hello.\", and run ...",delim,escap)<<"\r\n";
}
注意C语言的文字常量字符串中的转义符是\,编译成机器语言后,一般不会出现在存储中。
因此:源码中(此例子是非raw字符串,就是传统的字符串)的\"序列,编译器生成的是单字符"存储在文本常量区(或被拷贝到字符串string的内存里)。然后经过std::quoted的处理逻辑,生成""(两个双引号)的字符序列,被传送到ss流。