Programming in C

(Barry) #1
String-to-Number Conversion 479

int sprintf (buffer, format, arg1, arg2, ..., argn)
The specified arguments are converted according to the format specified by the char-
acter string format(see Chapter 16) and are placed into the character array pointed
to by buffer.A null character is automatically placed at the end of the string inside
buffer.The number of characters placed into bufferis returned, excluding the ter-
minating null. As an example, the code
int version = 2;
char fname[125];

sprintf (fname, "/usr/data%i/2005", version);
results in the character string "/usr/data2/2005"being stored in fname.
int sscanf (buffer, format, arg1, arg2, ..., argn)
The values as specified by the character string formatare read from bufferand
stored in the corresponding pointer arguments that follow format(see Chapter 16).
The number of items successfully converted is returned by this function. As an exam-
ple, the code
char buffer[] = "July 16, 2004", month[10];
int day, year;

sscanf (buffer, "%s %d, %d", month, &day, &year);
stores the string "July"inside month, the integer value 16 inside day, and the integer
value 2004 inside year.The code
#include <stdio.h>
#include <stdlib.h>

if ( sscanf (argv[1], "%f", &fval) != 1 ) {
fprintf (stderr, "Bad number: %s\n", argv[1]);
exit (EXIT_FAILURE);
}
converts the first command-line argument (pointed to by argv[1]) to a floating-
point number, and checks the value returned by sscanfto see if a number was suc-
cessfully read from argv[1]. (See the routines described in the next section for other
ways to convert strings to numbers.)

String-to-Number Conversion


The following routines convert character strings to numbers.To use any of the routines
described here, include the header file <stdlib.h>in your program:
#include <stdlib.h>

21 0672326663 AppB 6/10/04 2:03 PM Page 479

Free download pdf