Monday, July 27, 2009

Character String Help in C?

I have a problem with character string manipulation, im trying to prompt the user to enter a float (i.e. a numerical value) but the user can decide to close the program if he/she enters "exit". I tried using the isdigit and isalpha functions, but they only return a value of 0, which would force me to re-prompt the user. Any suggestions on how to immediately quit the program once the user enters "exit" ?

Character String Help in C?
Read in the character array (string) value and then test it being equal to exit. If not, then use the atof() function to try and convert the value to a float.





For example,





char myChar[20];


float myVal=0.0;


scanf("%s",myChar);





if (strcmp(myChar,"exit")) {


/* input is NOT equal to exit */


myVal = atof(myChar);


...





myVal would then contain the numerical value of their input according to the conversion rules of atof().





(massiv_x: a "string" is a character array terminated by a null character; what you've given is actually in error because you've defined 27 bytes, BUT because the value is enclosed in double-quotes, it stores 28 bytes (including the null terminator.) You can't use any string functions with that variable as it doesn't contain space for the string terminator \0. Perhaps just a typo. ;)
Reply:if i recall...the isdigit and isalpha function take only a single value...





in c, strings are actually just character arrays...you know:


char thisstring[27] = "twenty-seven bytes of data.";





in order for your method to work, youll have to pass in every letter on by one...this wont work for your cause tho..


when you pass the values into isalpha or isdigit you have to use the array index with the string variable..if you dont, youre just passing in a memory pointer value..this may work for you, you just gotta access the array (string) directly from memory using pointers..


No comments:

Post a Comment