×
Namespaces

Variants
Actions
Revision as of 10:43, 18 June 2012 by hamishwillee (Talk | contribs)

Archived:Converting numbers to C strings

From Nokia Developer Wiki
Jump to: navigation, search

Archived.pngArchived: This article is archived because it is not considered relevant for third-party developers creating commercial solutions today. If you think this article is still relevant, let us know by adding the template {{ReviewForRemovalFromArchive|user=~~~~|write your reason here}}.

Article Metadata
Tested with
Devices(s): Nokia N93
Compatibility
Platform(s): S60 3rd Edition, FP1
S60 3rd Edition (initial release)
Article
Keywords: sprintf(), snprintf()
Created: nymanaki (04 Apr 2008)
Last edited: hamishwillee (18 Jun 2012)

Contents

Overview

sprintf() and snprintf() functions can be used in Open C to convert numeric values into formatted numeral strings. Both of these functions return the number of characters printed.

  • sprintf() takes three parameters. The first holds the converted number, the second parameter is a string containing a format specifier, and the third is the number the user wants to convert into a string.
  • snprintf() is a safer version of sprintf() because there is also a fourth size parameter. snprintf() writes at most the given size-1 of the characters printed into the output string.


Note: In order to use this code, you need to install Open C plug-in.

This snippet can be self-signed.

MMP file

The following libraries are required:

LIBRARY libc.lib

Source file

#include <stdio.h> // sprintf(), snprintf()
 
#define MAX_STR_LEN 8
 
int main(void)
{
int printed = 0;
char numeral_string[MAX_STR_LEN];
 
/* - sprintf() - */
printed = sprintf(numeral_string, "%d", 123);
printf("123 in decimal is %s\n", numeral_string);
printf("printed characters: %d\n", printed);
 
printed = sprintf(numeral_string, "%x", 123);
printf("123 in hexadecimal is %s\n", numeral_string);
printf("printed characters: %d\n", printed);
 
/* - snprintf() - */
printed = snprintf(numeral_string, 7, "%o", 123);
printf("123 in octal is %s\n", numeral_string);
printf("printed characters: %d\n", printed);
 
/* only first three characters + trailing \0 is written to the buffer */
printed = snprintf(numeral_string, 4, "%d", 1234567890);
printf("123|4567890 in decimal is %s\n", numeral_string);
printf("printed characters: %d\n", printed);
 
return 0;
}

Postconditions

Four different number to string conversions are executed and displayed to the standard output.

63 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×