我已经尝试了几件事,
std::stringstream m;
m.empty();
m.clear();
Run Code Online (Sandbox Code Playgroud)
两者都不起作用.
当我会用std::istringstream,std::ostringstream以及std::stringstream为什么不应该我只是用std::stringstream在所有情况(是否有任何的运行时性能问题?).
最后,这有什么不好的(而不是使用流):
std::string stHehe("Hello ");
stHehe += "stackoverflow.com";
stHehe += "!";
Run Code Online (Sandbox Code Playgroud) 我的问题可以归结为,字符串从stringstream.str().c_str()内存中返回的字符串在哪里,为什么不能将其分配给const char*?
这个代码示例将比我更好地解释它
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream ss("this is a string\n");
string str(ss.str());
const char* cstr1 = str.c_str();
const char* cstr2 = ss.str().c_str();
cout << cstr1 // Prints correctly
<< cstr2; // ERROR, prints out garbage
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
stringstream.str().c_str()可以分配给a 的假设const char*导致我花了一段时间追踪的错误.
对于奖励积分,任何人都可以解释为什么替换cout声明
cout << cstr // Prints correctly
<< ss.str().c_str() // Prints correctly
<< cstr2; // Prints correctly (???)
Run Code Online (Sandbox Code Playgroud)
正确打印字符串? …
我有以下代码:
std::string str = "abc def,ghi";
std::stringstream ss(str);
string token;
while (ss >> token)
{
printf("%s\n", token.c_str());
}
Run Code Online (Sandbox Code Playgroud)
输出是:
abc
def,ghi
因此,stringstream::>>运算符可以按空格分隔字符串,但不能用逗号分隔.反正有没有修改上面的代码,以便我可以得到以下结果?
输入:"abc,def,ghi"
输出:
abc
def
ghi
如何从C++ 转换std::stringstream为std::string?
我是否需要在字符串流上调用方法?
stringstream parser;
parser << 5;
short top = 0;
parser >> top;
parser.str(""); //HERE I'M RESETTING parser
parser << 6; //DOESN'T PUT 6 INTO parser
short bottom = 0;
parser >> bottom;
Run Code Online (Sandbox Code Playgroud)
为什么不起作用?
为什么这一行会出错Error: incomplete type is not allowed?
stringstream ss;
Run Code Online (Sandbox Code Playgroud) 我在我的程序中有这个函数将整数转换为字符串:
QString Stats_Manager::convertInt(int num)
{
stringstream ss;
ss << num;
return ss.str();
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行这个时,我得到错误:
aggregate 'std::stringstream ss' has incomplete type and cannot be defined
Run Code Online (Sandbox Code Playgroud)
我不确定这意味着什么.但如果您知道如何修复它或需要更多代码,请发表评论.谢谢.
如何将字符串流的状态"重置"为创建它时的状态?
int firstValue = 1;
int secondValue = 2;
std::wstringstream ss;
ss << "Hello: " << firstValue;
std::wstring firstText(ss.str());
//print the value of firstText here
//How do I "reset" the stringstream here?
//I would like it behave as if I had created
// stringstream ss2 and used it below.
ss << "Bye: " << secondValue;
std::wstring secondText(ss.str());
//print the value of secondText here
Run Code Online (Sandbox Code Playgroud) 我最近发现std::strstream有人不赞成使用std::stringstream.自从我使用它已经有一段时间了,但它确实做了我当时需要做的事情,所以听到它的弃用感到惊讶.
我的问题是为什么做出这个决定,以及没有std::stringstream提供哪些好处std::strstream?