谁能解释一下下面的代码是如何工作的,并不会不应用程序崩溃?C++字符串流为char *转换内存分配
int main() {
char *tempStr = new char[5];
tempStr[0] = '\0';
string stemp = "helloworld";
stringstream sstream;
sstream.str(stemp);
cout << "len before = " << strlen(tempStr);
sstream >> tempStr;
cout << "len after = " << strlen(tempStr) << endl;
cout << tempStr << endl;
delete[] tempStr;
return 1;
}
我得到的输出作为
len before = 0
len after = 10
helloworld
- 没有
stringstream
在字符指针多余的字符分配内存? - 也想知道正确的方式从
stringstream
复制数据到char *数组,不超过分配给char*
内存?
我们还可以做's stemp'吗? – 0x499602D2
是的,因为它是用于输入和输出的'stringstream'。 – Nawaz
我有一个要求,不能使用字符串。所以唯一的方法是使用'istream :: read'并指定char数组的最大长度。谢谢。 – N3Xg3N