需要的toString()的C字符串格式
如果您只是需要的toString()的輸出轉換,你可以使用
const char* s = toString().c_str();
您的函數當前正在返回一個string
(我猜你的代碼有using namespace std
)這意味着一個C++字符串對象。
如果你不是絕對需要C字符串,我會推薦使用C++字符串,因爲它們更加現代,並且更容易使用。的char
但是,如果原因在代碼中的其他地方,你做需要一個C字符串,你的函數應該像
char* toString() {
// formatting your output
}
因爲所有的C字符串時爲空終止('\0'
)陣列,以及數組相當於指向第一個元素的指針,所以這就是char*
的來源。
無論哪種情況,C++ stringstreams都會使輸出格式更加直觀。你將需要#include <sstream>
,然後一些谷歌搜索將引導你在正確的方向。該解決方案也作品,如果你需要一個C字符串,因爲C++字符串有一個名爲c_str()
方法是C++字符串轉換成C字符串(字符的空終止數組):
#include <string>
#include <sstream>
using namespace std;
char* toString() {
stringstream ss; // these are so useful!
if (*d != 1) {
// this probably isn't the exact formatting you are looking for,
// but stringstreams can certainly do it if you research a bit!
ss << *n << *d;
}
else {
ss << *n;
}
string output = ss.str();
return output.c_str();
}
凡做'N'和'd '從哪裏來? – ShadowRanger
對不起,私人:int * n,* d。 – user5966606
所以這是一些現有類的方法。可能有助於看到足夠的班級瞭解結構。而且,目標本身有點不清楚。這是你想寫的功能嗎?還是你想寫一個單獨的函數,返回一個C風格的字符串?或者使用這個函數,然後轉換爲C風格的字符串? – ShadowRanger