在一行中连接多个字符串 C++
concating multiple strings in one line c++
我试图重载运算符“<<”以获得与 std::stringstream 类似的行为。
我想在一行中连接多个字符串,并将它们传递给行中最后一个单词后的另一个函数。
struct Log
{
std::string outString;
template<typename T>
friend Log& operator<<(Log& log, const T& t)
{
std::stringstream temp;
temp << t;
std::string str = temp.str();
log.outString += str;
if(str == "endl" || str == "\n")
{
//end of line -> pass string to custom print function
}
return log;
}
};
我在这一行中遇到分段错误:
log.outString += str;
应该这样称呼
log << "blub: " << 123 << "endl";
您正在比较语句 if(t == "endl" || t== "\n")
中的整数,请将其替换为 if(str == "endl" || str == "\n")
。
完整代码如下:
#include <iostream>
#include <string>
#include <sstream>
struct Logg
{
std::string outString;
template<typename T>
friend Logg& operator<<(Logg& logg, const T& t)
{
std::stringstream temp;
temp << t;
std::string str = temp.str();
logg.outString += str;
if(str == "endl" || str == "\n")
{
//end of line -> pass string to custom print function
}
return logg;
}
};
int main()
{
struct Logg logg;
logg << "blub: " << 123 << "endl";
std::cout << logg.outString << std::endl;
return 0;
}
我试图重载运算符“<<”以获得与 std::stringstream 类似的行为。 我想在一行中连接多个字符串,并将它们传递给行中最后一个单词后的另一个函数。
struct Log
{
std::string outString;
template<typename T>
friend Log& operator<<(Log& log, const T& t)
{
std::stringstream temp;
temp << t;
std::string str = temp.str();
log.outString += str;
if(str == "endl" || str == "\n")
{
//end of line -> pass string to custom print function
}
return log;
}
};
我在这一行中遇到分段错误:
log.outString += str;
应该这样称呼
log << "blub: " << 123 << "endl";
您正在比较语句 if(t == "endl" || t== "\n")
中的整数,请将其替换为 if(str == "endl" || str == "\n")
。
完整代码如下:
#include <iostream>
#include <string>
#include <sstream>
struct Logg
{
std::string outString;
template<typename T>
friend Logg& operator<<(Logg& logg, const T& t)
{
std::stringstream temp;
temp << t;
std::string str = temp.str();
logg.outString += str;
if(str == "endl" || str == "\n")
{
//end of line -> pass string to custom print function
}
return logg;
}
};
int main()
{
struct Logg logg;
logg << "blub: " << 123 << "endl";
std::cout << logg.outString << std::endl;
return 0;
}