我们可以在C编程中将数字转换为字符串吗?

时间:2017-07-21 16:17:58

标签: c

我试过这个,但它对我不起作用?

代码如下所示:

char result[50];

float n= 23.56;

printf(result, "%f", n);

printf("\n The string for the n is %s", result);

输出:The string for the n is

我没有得到答案。

3 个答案:

答案 0 :(得分:3)

使用sprintf()代替printf()。更好的是,使用snprintf()来指定字符串的长度。

#include <stdio.h>

int main()
{
    char result[50];

    float f = 23.56;

    // Your code uses printf()
    // printf(result, "%f", f);

    // Use sprintf() instead!
    sprintf(result, "%f", f);

    // Whenever possible, use snprintf()!
    // snprintf(result, 50, "%f", f);

    printf("\n f = %s\n", result);

    return 0;
}

为什么snprintf()优于sprintf() 简短的回答是snprintf()可以安全地防止缓冲区溢出攻击。

参考文献:

答案 1 :(得分:0)

使用sprintf代替打印。喜欢这个

sprintf (result,"%f",n)

答案 2 :(得分:-1)

如果我记得正确的语法:

int main()
{
    char result[50];
    float n = 23.56;
    ftoa(n, result, 4);
    printf("\n\"%s\"\n", result);
    return 0;
}

&#13;
&#13;
// C program for implementation of ftoa()
#include<stdio.h>
#include<math.h>

// reverses a string 'str' of length 'len'
void reverse(char *str, int len)
{
	int i=0, j=len-1, temp;
	while (i<j)
	{
		temp = str[i];
		str[i] = str[j];
		str[j] = temp;
		i++; j--;
	}
}

// Converts a given integer x to string str[]. d is the number
// of digits required in output. If d is more than the number
// of digits in x, then 0s are added at the beginning.
int intToStr(int x, char str[], int d)
{
	int i = 0;
	while (x)
	{
		str[i++] = (x%10) + '0';
		x = x/10;
	}

	// If number of digits required is more, then
	// add 0s at the beginning
	while (i < d)
		str[i++] = '0';

	reverse(str, i);
	str[i] = '\0';
	return i;
}

// Converts a floating point number to string.
void ftoa(float n, char *res, int afterpoint)
{
	// Extract integer part
	int ipart = (int)n;

	// Extract floating part
	float fpart = n - (float)ipart;

	// convert integer part to string
	int i = intToStr(ipart, res, 0);

	// check for display option after point
	if (afterpoint != 0)
	{
		res[i] = '.'; // add dot

		// Get the value of fraction part upto given no.
		// of points after dot. The third parameter is needed
		// to handle cases like 233.007
		fpart = fpart * pow(10, afterpoint);

		intToStr((int)fpart, res + i + 1, afterpoint);
	}
}

// driver program to test above funtion
int main()
{
	char res[20];
	float n = 34.5;
	ftoa(n, res, 4);
	printf("\n\"%s\"\n", res);
	return 0;
}
&#13;
&#13;
&#13;