Saturday, May 22, 2010

Seperating digits in a string, so they can be converted to integers in C?

this is what i got so far


int likeness(int user1,int user2)/*NOT FINISHED*/


{


int like=100,x;


char *temp,TEMP[20],Temp[1];


int temp1[20],temp2[20];


strcpy(TEMP,user_data[user1].question...


for(x=0;x%26lt;20;x++)


{


temp=TEMP[x];


temp1[x]=atoi(temp);


}


strcpy(temp,user_data[user2].question...


for(x=0;x%26lt;20;x++)


{


Temp[0]=TEMP[x];


temp2[x]=atoi(temp);


}


for(x=0;x%26lt;20;x++)


{


if(temp1[x]!=temp2[x])


like=like-(abs(temp1[x]-temp2[x]));


}


return like;


}


note: user_data is the database file


temp is temporary varibles

Seperating digits in a string, so they can be converted to integers in C?
I'm not sure I completely understand. So every single digit needs to be a separate integer? For example, if you receive 1932 as input do you want 4 integers...1, 9, 3, 2? If so, it would be something more like:


/*


* This is assuming you don't know the length of the


* input string. If you're sure it's 20 chars, then you


* can use a static array of 20 chars like you did. You


* also wouldn't need to do any freeing, etc.


*/


int likeness(int user1, int user1) {


int like = 100;


int x;


char singleDigit[2];


char *input1 = NULL;


char *input2 = NULL;


int temp1;


int temp2;





input1 = strdup(user_data[user1].q...);


if (!input1) {


/* Memory allocation failure... */


/* You can do something here if you want */


}





input2 = strdup(user_data[user2].q...);


if (!input2) {


/* Memory allocation failure... */


/* You can do something here if you want */


}





/*


* This loop assumes input1 and input2 are


* the same length. You might want to check


* the truth in this, etc. but for now...


*/


for (x = 0; x %26lt; strlen(input1); ++x) {


singleDigit[0] = input1[x];


singleDigit[1] = '\0';





temp1 = atoi(singleDigit);





singleDigit[0] = input2[x];


singleDigit[1] = '\0';





temp2 = atoi(singleDigit);





if (temp1 != temp2) {


like = like - abs(temp1 - temp2);


}


}





/* Free up memory */


if (input1) {


free(input1);


}





if (input2) {


free(input2);


}





return like;


}





I haven't compiled this so it isn't guaranteed to work the way you want. Basically you look ok except you can condense your loops and if you use atoi the way you are, you're going to have problems. The atoi function expects the string parameter to be null-terminated (i.e. you need a '\0' on the end).
Reply:Haven't done C in quite a while. But have you researched the MID$ function, I know you can extract any amount of a string with that command. And I can't believe that C doesn't have that command.


No comments:

Post a Comment