将浮点数转换为字符串

20

如何在C/C++中将浮点整数转换为字符串而不使用库函数 sprintf

我正在寻找一个函数,例如char *ftoa(float num),它将num转换为字符串并返回它。

ftoa(3.1415)应该返回"3.1415"


1
C语言中有浮点数转换为字符的功能,例如sprintf(a, "%d", f) - Hans W
一个解决方案:http://www.edaboard.com/ftopic41714.html#160029 - tur1ng
只需使用 sprint 函数来格式化浮点值。 - John Lawlor
12个回答

0
// This working code does:
// 1. Does not use sprintf as requested.
// 2. Gets some wide text from an editbox4 in VS2017
// 3. Converting that text to a double floating point number
// 4. Converts number to a wide string using ISO format, (StringCbPrintf replaced sprintf)
// 5. Transfers that text number back to another editbox5 for confirmation display as text
//
int const arraysize = 30;
wchar_t szItemName[arraysize]; // receives name of item
   if (!GetDlgItemText(hwnd, IDC_EDIT4, szItemName, arraysize )) *szItemName = 0;

double value = _wtof(szItemName);
wchar_t szname2[arraysize];

size_t cbDest = arraysize * sizeof(WCHAR);
LPCTSTR pszFormat = TEXT("%f");
HRESULT hr = StringCbPrintf(szname2, cbDest, pszFormat,value); //ISO format has buffer checking

SetDlgItemTextW(hwnd, IDC_EDIT5, szname2);


-2

1
本站通常不接受仅包含链接的答案。 - MD XF

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接