Join Now
Quality Rating:
  • Currently 0.0 / 5
(0.0 / 5 - 0 votes cast)
Expertise Level:
  • Currently 0.0 / 5
(0.0 / 5 - 0 votes cast)

This page was last modified 06:51, 17 April 2008.

CS000897 - Converting numbers to C strings

From Forum Nokia Wiki


ID CS000897 Creation date April 17, 2008
Platform S60 3rd Edition, FP1 Tested on devices Nokia N93
Category Open C Subcategory Files/Data


Keywords (APIs, classes, methods, functions): sprintf(), snprintf()

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.

Related Discussions
Thread Thread Starter Forum Replies Last Post
WAP - access local phone numbers Nokia_Archive Browsing and Mark-ups 1 2002-05-15 19:46
Distinguishing mobile nos and telephone nos in Contacts DB cmc77 General Symbian C++ 1 2004-03-15 08:25
Nokia 3200 DarkSyphon General Discussion 2 2006-05-02 15:16
Serious problem with Strinng on S60 with midp 1.0 kavaja Mobile Java General 1 2005-02-01 09:20
Unicode resource files simworks Symbian Tools & SDKs 4 2005-07-06 21:15
 
Powered by MediaWiki