我正在尝试将stringstream
转换为const char*
,但是我总是得到一个空白字符串。
我的代码:
#include<string>
#include<sstream>
#include<stdio.h>
const char* test(std::string city, std::string street, int houseNumber, int postCode) {
std::stringstream ss;
ss << city << " " << street << " " << houseNumber << " " << postCode;
const std::string tmp = std::string{ss.str()};
const char* str = tmp.c_str();
return str;
}
int main(){
printf(test("demo", "Demo", 1, 1234));
}
预期输出:demo Demo 1 1234
我尝试了How to convert a std::string to const char* or char*?中提到的所有增强功能,但没有成功。
答案 0 :(得分:3)
问题是您的const char*
指向的字符串数据已在return str;
之后释放。只要关联的const char*
实例在范围内,std::string
指针将保持有效。假设您在此处显示的代码位于函数内。在这种情况下,字符串tmp
将在return str;
之后超出范围,并且其析构函数将被调用,导致指向其字符数据的所有指针都变为dangling pointer。>
相反,返回std::string
,然后对返回的字符串调用c_str()
。如前所述,只要关联的const char*
实例在范围内,就可以使用std::string
指针。
答案 1 :(得分:1)
您可以使用<a href='http://localhost:3000/quotes/' + @quote.id>Show</a>
存储临时对象,从而将悬空引用转换为非悬空引用。
请注意,您一次只能有一个活动的“非悬挂”参考:
static thread_local
预期输出:
#include <string>
#include <sstream>
#include <iostream>
const char* to_cstr(std::string && s)
{
static thread_local std::string sloc;
sloc = std::move(s);
return sloc.c_str();
}
const char* make_address(std::string const& city,
std::string const& street,
std::string const& houseNumber,
std::string const& postCode)
{
std::stringstream ss;
ss << city << " " << street << " " << houseNumber << " " << postCode;
return to_cstr(std::move(ss).str());
}
int main()
{
const char* p = make_address("London","Bob Street","42","W1ABC");
std::cout << p << std::endl;
}
答案 2 :(得分:0)
您遇到的问题是,当此函数离开作用域(即执行return str;
时),指向str
的内存将被清除。您需要返回一个对象,该对象将保持对数据的所有权。
//std::string_view is >=c++17, use std::string const& for older compilers
std::string get_formatted_address(
std::string_view city,
std::string_view street,
std::string_view houseNumber,
std::string_view postCode
) {
std::stringstream ss;
ss << city << " " << street << " " << houseNumber << " " << postCode;
return ss.str();
}
int main() {
auto city = "New York", street = "Rockefeller Lane", houseNumber = "1234", postcode = "56789";
auto formatted_address = get_formatted_address(city, street, houseNumber, postcode);
//Here, formatted_address holds ownership over the memory, so calling c_str is safe
printf("Address: %s\n", formatted_address.c_str());
}