C/String/String Convert — различия между версиями
Admin (обсуждение | вклад) м (1 версия: Импорт контента...) |
|
(нет различий)
|
Текущая версия на 10:22, 25 мая 2010
Содержание
- 1 Absolute value of long integer: how to use labs
- 2 Change string to integer
- 3 Convert one or more floating-point values into a single string
- 4 Convert string entered to integer
- 5 Convert string entered to long
- 6 Convert string to double: how to use atof
- 7 Convert string to double: How to use atof: sines calculator
- 8 Convert string to double-precision floating-point value
- 9 Convert string to double-precision floating-point value: how to use strtod
- 10 Convert string to int, double and long
- 11 Convert string to integer: atoi
- 12 Convert string to long : atol
- 13 Convert string to long integer: how to use strtol
- 14 Convert string to unsigned long integer: how to use strtoul
- 15 Join array of strings into a single string
- 16 Print formatted data to a string: how to use sprintf
Absolute value of long integer: how to use labs
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int n, m;
n = labs( 65537 );
m = labs( -110000 );
printf ("n = %d \n", n);
printf ("m = %d\n", m);
return 0;
}
Change string to integer
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char num[80];
gets(num);
printf("%d", abs( atoi( num ) ) );
return 0;
}
Convert one or more floating-point values into a single string
/*
Beginning C, Third Edition
By Ivor Horton
ISBN: 1-59059-253-0
Published: Apr 2004
Publisher: apress
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
char* to_string(int count, double first, ...); /* Converts doubles to a string separated by commas */
char* fp_to_str(double x); /* Converts x to a string */
char* int_to_str(int n); /* Converts n to a string */
void main()
{
char *str = NULL; /* Pointer to the string of values */
double values[] = { 1.245, -3.5, 6.758, 33.399, -1.02 };
str = to_string(sizeof values/sizeof(double), values[0], values[1], values[2], values[3], values[4]);
printf("The string of values is:\n%s\n", str);
free(str); /* Free memory for string */
}
/************
* Function to convert one or more floating-point values to a *
* string with the values separated by commas. *
* This function allocates memory that must be freed by the caller *
************/
char* to_string(int count, double first, ...)
{
va_list parg = NULL; /* Pointer to variable argument */
char* str = NULL; /* Pointer to the joined strings */
char *temp = NULL; /* Temporary string pointer */
char *value_str = 0; /* Pointer to a value string */
const char *separator = ","; /* Separator in values string */
size_t separator_length = 0; /* Length of separator string */
size_t length = 0; /* Length of a string */
int i = 0; /* Loop counter */
separator_length = strlen(separator);
va_start(parg,first); /* Initialize argument pointer */
str = fp_to_str(first); /* convert the first value */
/* Get the remaining arguments, convert them and append to the string */
while(--count>0)
{
value_str = fp_to_str(va_arg(parg, double)); /* Get next argument */
length = strlen(str) + strlen(value_str) + separator_length +1;
temp = (char*)malloc(length); /* Allocate space for string with argument added */
strcpy(temp, str); /* Copy the old string */
free(str); /* Release old memory */
str = temp; /* Store new memory address */
temp = NULL; /* Reset pointer */
strcat(str,separator); /* Append separator */
strcat(str,value_str); /* Append value string */
free(value_str); /* Release value string memory */
}
va_end(parg); /* Clean up arg pointer */
return str;
}
/********************
* Converts the floating-point argument to a string. *
* Result is with two decimal places. *
* Memory is allocated to hold the string and must be freed by the caller. *
********************/
char* fp_to_str(double x)
{
char *str = NULL; /* Pointer to string representation */
char *integral = NULL; /* Pointer to integral part as string */
char *fraction = NULL; /* Pointer to fractional part as string */
size_t length = 0; /* Total string length required */
integral = int_to_str((int)x); /* Get integral part as a string with a sign */
/* Make x positive */
if(x<0)
x = -x;
/* Get fractional part as a string */
fraction = int_to_str((int)(100.0*(x+0.005-(int)x)));
length = strlen(integral)+strlen(fraction)+2; /* Total length including point and terminator */
/* Fraction must be two digits so allow for it */
if(strlen(fraction)<2)
++length;
str = (char*)malloc(length); /* Allocate memory for total */
strcpy(str, integral); /* Copy the integral part */
strcat(str, "."); /* Append decimal point */
if(strlen(fraction)<2) /* If fraction less than two digits */
strcat(str,"0"); /* Append leading zero */
strcat(str, fraction); /* Append fractional part */
/* Free up memory for parts as strings */
free(integral);
free(fraction);
return str;
}
/********************
* Converts the integer argument to a string. *
* Memory is allocated to hold the string and must be freed by the caller. *
********************/
char* int_to_str(int n)
{
char *str = NULL; /* pointer to the string */
int length = 1; /* Number of characters in string(at least 1 for terminator */
int temp = 0;
int sign = 1; /* Indicates sign of n */
/* Check for negative value */
if(n<0)
{
sign = -1;
n = -n;
++length; /* For the minus character */
}
/* Increment length by number of digits in n */
temp = n;
do
{
++length;
}
while((temp /= 10)>0);
str = (char*)malloc(length); /* Allocate space required */
if(sign<0) /* If it was negative */
str[0] = "-"; /* Insert the minus sign */
str[--length] = "\0"; /* Add the terminator to the end */
/* Add the digits starting from the end */
do
{
str[--length] = "0"+n%10;
}while((n /= 10) > 0);
return str;
}
Convert string entered to integer
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char num1[80], num2[80];
printf("Enter first: ");
gets(num1);
printf("Enter second: ");
gets(num2);
printf("The sum is: %d.", atoi(num1) + atoi(num2));
return 0;
}
Convert string entered to long
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char num1[80], num2[80];
printf("Enter first: ");
gets(num1);
printf("Enter second: ");
gets(num2);
printf("The sum is: %ld.", atol(num1)+atol(num2));
return 0;
}
Convert string to double: how to use atof
#include <stdio.h>
#include <math.h>
int main ()
{
double n, m;
double pi = 3.1415926535;
char str[256];
printf ( "Enter degrees: " );
gets ( str );
n = atof ( str );
m = sin (n * pi / 180);
printf ( "sine of %f degrees = %f\n" , n, m );
return 0;
}
Convert string to double: How to use atof: sines calculator
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main ()
{
double n, m;
double pi=3.1415926535;
char str[256];
printf ( "Enter degrees: " );
gets ( str );
n = atof ( str );
m = sin ( n * pi / 180 );
printf ( " sine of %f degrees = %f \n" , n, m );
return 0;
}
Convert string to double-precision floating-point value
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
int main(void)
{
char *end, *start = "Value: 111.1111111";
end = start;
while( *start ) {
printf("%f, ", strtod(start, &end));
printf("Remainder: %s\n" ,end);
start = end;
/* move past the non-digits */
while(!isdigit(*start) && *start)
start++;
}
return 0;
}
Convert string to double-precision floating-point value: how to use strtod
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char str[256];
char *p;
double dbl;
printf ("Enter a floating-point value: ");
gets (str);
dbl = strtod (str, &p);
printf ("Value entered: %lf. Its square: %lf\n", dbl, dbl * dbl);
return 0;
}
Convert string to int, double and long
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i;
double d;
long l;
i = atoi("1");
l = atol("11111111");
d = atof("11111.11111");
printf("%d %ld %f", i, l, d);
return 0;
}
Convert string to integer: atoi
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char str[256];
printf ("Enter a number: ");
gets ( str );
i = atoi ( str );
printf ("i = %d, its double = %d", i, i * 2 );
return 0;
}
Convert string to long : atol
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char str[256];
printf ("Enter a long number: ");
gets ( str );
i = atol ( str );
printf ("i = %d, its double = %d", i, i * 2 );
return 0;
}
Convert string to long integer: how to use strtol
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char str[256];
char *p;
long l;
printf ("Enter an long value: ");
gets (str);
l = strtol (str, &p, 0);
printf ("Value entered: %ld. Its double: %ld\n", l, l * 2);
return 0;
}
Convert string to unsigned long integer: how to use strtoul
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char str[256];
char *p;
unsigned long ul;
printf ("Enter an integer value: ");
gets (str);
ul = strtoul (str, &p, 0);
printf ("Value entered: %lu. Its double: %lu\n", ul, ul * 2);
return 0;
}
Join array of strings into a single string
/*
Beginning C, Third Edition
By Ivor Horton
ISBN: 1-59059-253-0
Published: Apr 2004
Publisher: apress
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_STRINGS 100 /* Maximum string count */
#define BUFFER_SIZE 50 /* Initial input buffer size */
char* join_strings(char *strings[], int count); /* Joins array of strings into a single string */
char* read_string(); /* Reads a string from the keyboard */
void main()
{
char *pStrings[MAX_STRINGS]; /* Array of pointers to strings */
char *joined_strings = NULL; /* Pointer to the joined string */
int count = 0; /* Number of strings entered */
char answer = "y"; /* Confirms more input */
char terminator = "*"; /* Terminator for string entry */
int i = 0;
/* Read the strings */
while(count<MAX_STRINGS && tolower(answer)=="y")
{
printf("Enter a string:\n");
pStrings[count++] = read_string(terminator);
printf("Do you want to enter another: ");
scanf(" %c", &answer);
fflush(stdin); /* Lose newline following character entry */
}
joined_strings = join_strings(pStrings, count);
printf("\nHere are the strings as a single string:\n%s\n", joined_strings);
free(joined_strings); /* Free memory for joined strings */
for(i = 0 ; i<count ; i++) /* Free memory for original strings */
free(pStrings[i]);
}
/************
* Function to join an array of strings *
* this function allocates memory that must be freed by the caller *
************/
char* join_strings(char *strings[], int count)
{
char* str = NULL; /* Pointer to the joined strings */
size_t total_length = 0; /* Total length of joined strings */
size_t length = 0; /* Length of a string */
int i = 0; /* Loop counter */
/* Find total length of joined strings */
for(i = 0 ; i<count ; i++)
{
total_length += strlen(strings[i]);
if(strings[i][strlen(strings[i])-1] != "\n")
++total_length; /* For newline to be added */
}
++total_length; /* For joined string terminator */
str = (char*)malloc(total_length); /* Allocate memory for joined strings */
str[0] = "\0"; /* Empty string we can append to */
/* Append all the strings */
for(i = 0 ; i<count ; i++)
{
strcat(str, strings[i]);
length = strlen(str);
/* Check if we need to insert newline */
if(str[length-1] != "\n")
{
str[length] = "\n"; /* Append a newline */
str[length+1] = "\0"; /* followed by terminator */
}
}
return str;
}
/********************
* Reads a string of any length. *
* The string is terminated by the chracter passed as the argument. *
* Memory is allocated to hold the string and must be freed by the caller. *
********************/
char* read_string(char terminator)
{
char *buffer = NULL; /* Pointer to the input buffer */
int buffersize = BUFFER_SIZE; /* Current buffer capacity */
int length = 0; /* String length */
char *temp = NULL; /* Temporary buffer pointer */
int i = 0; /* Loop counter */
buffer = (char*)malloc(BUFFER_SIZE); /* Initial buffer */
/* Read the string character by character */
for(;;)
{
/* Check for string terminator */
if((buffer[length] = getchar()) == terminator)
break;
else
++length;
/* Check for buffer overflow */
if(length == buffersize)
{
buffersize += BUFFER_SIZE; /* Increase buffer size */
temp = (char*)malloc(buffersize); /* Allocate new buffer */
/* Copy characters from old buffer to new */
for(i = 0 ; i<length ; i++)
temp[i] = buffer[i];
free(buffer); /* Free memory for old buffer */
buffer = temp; /* Store new buffer address */
temp = NULL; /* Rest temp pointer */
}
}
buffer[length] = "\0"; /* Append string terminator */
temp = (char*)malloc(length+1); /* Allocate exact memory required for string */
strcpy(temp, buffer); /* Copy the string */
free(buffer); /* Free the buffer memory */
return temp;
}
Print formatted data to a string: how to use sprintf
#include <stdio.h>
int main ()
{
char buffer [50];
int n, a = 50, b = 37;
n = sprintf (buffer, "%d plus %d is %d", a, b, a + b);
printf ("[%s] is a %d chars string\n", buffer, n);
return 0;
}