Question:
c program help. convert to string?
Mike
2009-07-05 21:32:52 UTC
I have to convert the following part of my program to a string. This part of my program finds the number of positive elements in my array. What I have to convert to a string is what follows:

#include "list.h"

int posTween(double x[],int m, int n, int len) {
int count = 0;

n=MIN(n,len-1);
while (m <= n) {
if (x[m] > 0) count++;
m++;
}
return count;
}

/*any help would be appreciated*/. Thank you.
Three answers:
Oliver
2009-07-06 11:40:03 UTC
like llaffer said you will want sprintf() but the buffer (the char[]) you write to will have to be at least 12 bytes long to avoid overflows as an integer can hold (2^31)-1 to -(2^31), 2^31 is 10 characters long (2147483648) and a negative sign makes 11 characters long and finally you need the null terminator which makes 12 characters/bytes, also as count is an integer and not a real number. e.g.

char buffer[12];

sprintf(buffer,"%d",posTween(/* values here */));

if you are simply going to print the string to the console then you can skip the buffer and use

printf("%d",posTween(/* values here */))

or if you write it to a file then

fprintf(STDOUT,"%d",posTween(/* values here */));
llaffer
2009-07-05 21:54:03 UTC
I'm not sure exactly what you're trying to do there, but if you want to copy a numeric variable into a character array (there really is no "string" concept beyond that in C), you can use the following function:



int i = 100;

char str[5];

sprintf(str, "%d", i);



It's used similar to fprintf to putput to a file pointer, but sprintf is used to format an output into a "string".



If this isn't what you want to do, you'll have to elaborage more.
detar
2016-11-04 17:09:45 UTC
your application looks to truly be changing a single digit of decimal into hexadecimal (form of greater of only renaming 10 - 15 A - F) somewhat than going from hexadecimal to decimal in case you had to bypass from hexadecimal to decimal you are able to desire to accomplish a little element alongside the lines of int A = 10, B = 11, ...; then take the enter that they supply you and then have cin >> hexa; n = digit; deci += hexa * pow(sixteen, n); using a loop to ensure you get each and every digit or some element in case you already be responsive to the type of digits you ought to start from the utmost one or you're able to desire to start from the backside one till you decide on for to get the entire enter first


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...