简体   繁体   English

如何在stringstream中放置一个字符串

[英]How in to stringstream put a string

I have a vector: 我有一个向量:

vector<stringstream*> ssv;
for (int i = 0; i < cIter; i++) {
    ssv.push_back(new std::stringstream);
}

How can I put in elements of vector ssv strings? 如何输入向量svv字符串的元素?

I try: 我尝试:

string s1 = "easfef" + '\n';
int i = 0;
*ssv[i] << s1 << '\n';

But it give me an empty string: 但这给了我一个空字符串:

string sdf = ssv[i]->str();

How can I do it? 我该怎么做?

Thanks for helping with '\\n', but it is stil a problem with vector: if i write: 感谢您对'\\ n'的帮助,但这仍然是vector的问题:如果我这样写:

std::string s1 = "qwerqwr\n";   // for example
int i = 0;
*ssv[i] << s1;

But give me an empty string as before 但是像以前一样给我一个空字符串

string sdf = ssv[i]->str();

Your main problem is how you initialize the string: 您的主要问题是如何初始化字符串:

"easfef" + '\n'

The "easfef" decays into a const char * and '\\n' is promoted to an int with the value 10 (assuming ASCII). "easfef"衰减为const char *并将'\\n'提升为值为10的int (假定为ASCII)。 Then, the two are added together, which results in a pointer that points somewhere beyond your string literal. 然后,将两者加在一起,这将导致一个指向字符串文字之外的指针。 A crash is very possible, along with your mother being eaten by a dinosaur. 当您的母亲被恐龙吃掉时,极有可能发生车祸。

An easy way to fix this is to enforce std::string : 解决此问题的一种简单方法是强制执行std::string

std::string s1 = std::string("easfef") + '\n';

An easier way is to inline the newline: 一种更简单的方法是内联换行符:

std::string s1 = "easfef\n";

In your code 在你的代码中

string s1 = "easfef" + '\n';

the initialization expression will in practice compute as 初始化表达式实际上将计算为

"easfef" + 10;

which is a pointer to the eleventh character of the string. 这是指向字符串第11个字符的指针。

But there is no such, so you have Undefined behavior . 但是没有这样的,所以您有Undefined behavior


Fix: 固定:

string s1 = string() + "easfef" + '\n';

That said, a vector of pointers to stringstream is almost certainbly an impractical solution to whatever problem you're trying to solve. 也就是说,指向stringstream的指针向量几乎可以肯定地解决了您要解决的任何问题。

Try to describe the higher level problem. 尝试描述更高级别的问题。

In C++ string literals are raw arrays of chars , and arrays can be treated as pointers, and character literals like '\\n' can be treated as numbers, so "easfef" + '\\n' is interpreted as a pointer arithmetic operation. 在C ++中,字符串文字是chars的原始数组,并且数组可以视为指针,而像'\\ n'这样的字符文字可以视为数字,因此"easfef" + '\\n'被解释为指针算术运算。

You should write: 您应该写:

string s1 = "easfef";
s1 += '\n';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM