Can anyone refactor some of my code?
int ndigits(void) { typedef enum {false, true} bool; enum {NUMLENGTH = 100}; char* number = malloc(sizeof(number) * NUMLENGTH); unsigned char c; bool is_a_number; int i, digits; digits = i = 0; is_a_number = true; printf("Enter a real number (base 10): "); while ((c = getchar()) != '\n') { number[i++] = c; if (c != '-' && c != '.' && is_a_number) { if (c - '0' < 0 || c - '0' > 9) { is_a_number = false; } else { ++digits; } } } number[i] = '\0'; if (! is_a_number) { printf("%s is not a base 10 number.\n", number); } else { printf("The number %s has %d digits", number, digits); } free(number); return is_a_number; }
what do you mean refactor?
In the programming world, refactoring code basically means restructuring it while preserving its intended function.
and why you need to refactor? make it more optimal? but I'm not very familiar with C so I don't know if I will be able to
just to make it look prettier :-P
you mean in my other question? Nah, 3 dimensional vectors in C would simply be A[3];
I hate to break it to you, but no amount of refactoring will make C look like something other than C. ;P My best guess would be to break out the functionality into subroutines. AND ADD COMMENTS!
is it just me or are you returning a boolean for an int method?
yeah he do :D
it would also be difficult to refactor any code without some kind of scope of your requirements, other methods, intended purpose.....
@on2valhalla In C (at least... I don't know about C++ but I think C++ doesn't allow it), enum and int values can be mixed freely, so I can return is_a_number as an int even though it seems it's a 'bool'. all this code does is asks the user to enter a base-10 real number, and then it prints out the number of digits in that number.
@agdgdgdgwngo I checked your code (not quite in-depth), but still, and I have a tip and a notice: The tip is that maybe it would be better if you put the number checking in a different function. That way you can both reuse your code and add modularity to it. The notice is that your code is accepting arbitrary long sequences of dots and "e" and "f" characters (something like .eee.fef.e.f.e.e.fe.f.ef.e.fe.fe). I don't know how one could abuse this, but the bug is there. Maybe inputing hexadecimal values without the 0x identifier, really don't know. With that being said, I liked the fact that you remember to use free() at the end, deallocating heap memory :-). Kudos for making the program.
@bmp You're right I better keep track of the number of signs and dots
There's a million ways to skin a cat....and my way for this cat is attached. IMO it's more clear and should do what you want. HTH
yay thanks :-D
Join our real-time social learning platform and learn together with your friends!