Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

float to string using snprintf and stringstreams #14

Closed
joe31093 opened this issue Jan 28, 2017 · 2 comments
Closed

float to string using snprintf and stringstreams #14

joe31093 opened this issue Jan 28, 2017 · 2 comments
Labels

Comments

@joe31093
Copy link

When using snprintf to convert a float to a string, the call fails. Please see code and output below.
Hardware = Teensy3.6

#include <arduino.h>
int main()
{
	// Rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200
	Serial.begin(9600);

	int value1 = -12345;
	int value2 = 9876;
	float pi = 3.141596;
	char buffer[32];
	int copied = 0;

	while (true)
	{
		memset(buffer, 0x00, sizeof(buffer));
		copied = snprintf(buffer, sizeof(buffer), "%d", value1);
		Serial.print("copied: ");
		Serial.println(copied);
		Serial.print("buffer: ");
		Serial.println(buffer);

		memset(buffer, 0x00, sizeof(buffer));
		copied = snprintf(buffer, sizeof(buffer), "%d", value2);
		Serial.print("copied: ");
		Serial.println(copied);
		Serial.print("buffer: ");
		Serial.println(buffer);

		memset(buffer, 0x00, sizeof(buffer));
		copied = snprintf(buffer, sizeof(buffer), "%.4f", pi);
		Serial.print("copied: ");
		Serial.println(copied);
		Serial.print("buffer: ");
		Serial.println(buffer);

		delay(5000);
	}

	return 0;
}

Output:
copied: 6

buffer: -12345
copied: 4
buffer: 9876
copied: 0
buffer:

I tried using a template ostringstream method as well. It it crashes on ss << Number when the number is a float.

Code:

template std::string to_string(const T& Number)
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
@ivankravets
Copy link
Member

@joe31093
Copy link
Author

Just tried 2.4.0 and the code still exceptions. The line asm(".global _printf_float"); is still needed to make this work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants