c - Loop with simple counter malfunctioning? -
i have program takes char array , calls function convert. function determines whether character letter or number. program supposed output first letter finds in string. , first numbers finds in string. loop stop looking letters after finds 1 isn't working.
any thoughts? code written in c using borland compiler.
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <ctype.h> #include <string.h> int convert (char array[],char **); int main() { int intval; char array[512], *charptr; printf("input string starts series of decimal digits:\n>"); while ( gets( array ) != null ){ intval = convert(array, &charptr ); printf ("intval contains %d, charptr contains '%s'\n", intval, charptr); } system("pause"); return 0; } int convert (char array[],char ** charptr) { int i, x, c = 0; char b[512]; (i=0;i<strlen(array);i++){ if (isalpha(array[i])) { if(c >= 1){ *charptr = &array[i]; c++; } else break; } else if ( isdigit(array[i])) x = 10*x + array[i] - '0'; } return x; }
update:
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <ctype.h> #include <string.h> int convert (char array[],char ** charptr); int main() { int intval; char array[512], *charptr; printf("input string starts series of decimal digits:\n>"); while ( gets( array ) != null ){ intval = convert(array, &charptr ); printf ("intval contains %d, charptr contains '%s'\n", intval, charptr); } system("pause"); return 0; } int convert (char array[],char ** charptr) { int i, x, c; char b[512]; (i=0;array[i] != 0;i++){ if ( isdigit(array[i])) x = 10*x + array[i] - '0'; else if (isalpha(array[i])) { c++; if(c >= 1){ *charptr = &array[i]; } } } return x; }
you have logic error. c
initialized 0
. there line increment c
inside if
block never true.
if(c >= 1){ *charptr = &array[i]; c++; }
catch 22???
perhaps meant use:
int convert (char array[],char ** charptr) { int i, x, c = 0; char b[512]; (i=0;i<strlen(array);i++){ if (isalpha(array[i])) { // no need checking value of c // return find alphabet. *charptr = &array[i]; break; } else if ( isdigit(array[i])) // if looking alphabet only, // why have block of code??? x = 10*x + array[i] - '0'; } return x; }
update
perhaps, looking for.
int convert (char array[], char ** charptr) { size_t i; int x = 0; size_t len = strlen(array); // set charptr null in case there no letters in input. *charptr = null; (i=0;i<len;i++){ if ( isalpha(array[i])) { *charptr = &array[i]; return x; } else if ( isdigit(array[i])) { x = 10*x + array[i] - '0'; } } return x; }
Comments
Post a Comment