对于std::stringstream* 的使用:
#include <iostream>
#include <string>
#include <sstream>
void writerFun(std::stringstream* stream){
*stream << "xxx\n";
*stream << "yyy\n";
*stream << "zzz\n";
}
void writerFun2(std::stringstream* stream){
std::ostream *out;
out = stream;
*out << "xxx";
*out << "yyy";
*out << "zzz";
}
void readerFun(std::stringstream* stream){
std::string str;
while(*stream >> str){
std::cout << str << std::endl;
}
}
void readerFun2(std::stringstream* stream){
std::istream *read;
read = stream;
std::string str;
while(*read >> str){
std::cout << str << std::endl;
}
}
int main()
{
std::stringstream ss;
writerFun(&ss);
// writerFun2(&ss);
std::cout << ss.str();
// readerFun(&ss);
readerFun2(&ss);
}
字符串初始化Json文件,硬编码Json文件,ofstream、ifstream
#include <fstream>
#include <string>
#include <iostream>
int main() {
std::string str;
std::ifstream file("E:\\WorkSpace\\VS2019_WorkSpace\\CuraEngine_msvc2019\\test\\fdmprinter.def.json");
if (!file.is_open()) {
std::cout << "file open fail!!!" << std::endl;
}
while (file)
{
std::string s;
getline(file, s);
//std::cout << s + "/r/n" << std::endl;
str += s + R"(\r\n)" + "\n";
}
file.close(); //关闭文件输入流
std::ofstream out_file("E:\\WorkSpace\\VS2019_WorkSpace\\CuraEngine_msvc2019\\test\\data.txt");
if (!out_file.is_open()) {
std::cout << "file open fail!!!" << std::endl;
}
out_file << str;
out_file.close();
//std::cout << str << std::endl;
return 0;
}
C++ 长行字符串多行书写书写规范:
1.使用双引号
string testShader =
"uniform mat4 g_mvpMatrix; \n"
"attribute vec3 position;\n"
"void main ()\n"
"{\n"
"gl_Position = g_mvpMatrix * vec4(position.x, position.y, position.z, 1.0);\n"
"}\n";
缺点:需要每行都写‘\n’。更改后如果一行过长还须拆分成两行,比较麻烦。
2.在字符串换行处加一个反斜杠’\’
string testShader =
"uniform mat4 g_mvpMatrix;\n\
attribute vec3 position;\n\
void main ()\n\
{\n\
gl_Position = g_mvpMatrix * vec4(position.x, position.y, position.z, 1.0);\n\
}";
缺点:下一行前不能有空格或者Tab键,否则会有多余空格。需要每行都写‘\n’。
3.用带参数宏定义
#define MULTILINE(...) #__VA_ARGS__
...
string testShader = MULTILINE(
uniform mat4 g_mvpMatrix;\n
attribute vec3 position;\n
void main ()\n
{\n
gl_Position = g_mvpMatrix * vec4(position.x, position.y, position.z, 1.0);\n
}
);
缺点:想打多行的话仍然需要每行后写\n
4.C++11 Raw String Literals
string testShader = R"(uniform mat4 g_mvpMatrix;
attribute vec3 position;
void main ()
{
gl_Position = g_mvpMatrix * vec4(position.x, position.y, position.z, 1.0);
}
)";
这个方法最大的好处就是不用每一行打\n了。不过在大部分的文本编辑器中,代码可能会上色不正常。一个hack可以绕开代码上色不正常的问题。
5.使用 R""(…)""!!!!!!!
string testShader = R""(uniform mat4 g_mvpMatrix;
attribute vec3 position;
void main ()
{
gl_Position = g_mvpMatrix * vec4(position.x, position.y, position.z, 1.0);
}
)"";
不过这个方法只对某一些比较简单的文本编辑器有用。
通常每行都换行并非必要。这里仅将一段着色器代码作为例子使用。