C programming- Can someone help me understand my own solution?
-
//Start sample code int x=0,Input=0; char *Data="123456789"; char *Debug=malloc(Getstrlen(Debug)*1000); //Debugger variable fprintf(stdout,"Enter an integer value:"); //Request input fscanf(stdin,"%d",&Input); //code checks for invalid input. for(x;x<=Getstrlen(Data);) //int Getstrlen(char *String) return the length of Data. { if(Input==Data[x]) { gets(Debug);//catch input overflow. free(Debug); system("cls"); //clears screen(not relevent to the question) //Go back to request input. } x++; } //End sample code Ok,if you've ever written C code, at some point you'd have liked or wanted to validate a user's input instead of asking a user to not enter something invalid(because its embarrasing and sucks).You'll know theres no input validation built into the C language and if you enter an alphabeth/character instead of an integer your program will crap out.Theres just no way to check if a user actually entered a character.Using functions from ctype.h in an if statement is no use.So,out of curiousity and love for the lang,I decided to brainstorm some solutions for this.Suffice to say,the above code actually works(Test it and use it in your apps if you want)YaY :D.Problem is:I dont know/remember why.Now,I know its pretty stupid and laughable to ask other coders why your own code/solution works but I need help understanding me own code:P. Please dont flame me for not commenting enough.LOL. Thanks in advance.
-
Answer:
include <iostream> #include <cstdlib> #define BUFFERSIZE 128 // Integrated Development Environment // Visual C++ using namespace std; // your Getstrlen function size_t str_length(char* _str) { size_t _cnt; for (_cnt = 0; _str[_cnt] != 0; _cnt ++); return _cnt; } // C programming: // Can someone help me understand my own solution? void main(void) { int Input = 0; char *Data = "0123456789"; size_t len = str_length(Data); // malloc: allocate a memory. //char *Debug = (char*)malloc(BUFFERSIZE); // calloc: allocate and initialize memory. //char *Debug = (char*)calloc( BUFFERSIZE, sizeof(char)); // new: C++ allocate memory. char *Debug = new char[BUFFERSIZE]; FILE* fin = stdin; while ( true ) { // input printf("Enter an integer value (quit = \'q\'): "); fscanf( fin, "%c", (char*)&Input); // another way is string type. //char Input[2] = ""; //fscanf( fin, "%s", Input); strcpy( Debug, "It\'s not a numeric character."); for(size_t i = 0; i < len; i ++) { if( Input == Data[i] ) { // for stdin: // fflush(stdin) = rewind(stdin) // fin->_base is char type. strcpy( Debug, fin->_base); Debug[str_length(fin->_base) - 2] = 0; } } if ( Input == 'q' ) { break; } cout<<" Debug = "<<Debug<<endl; fflush(fin); system("PAUSE"); // clear screen system("CLS"); } fin = NULL; // flush stdin fflush(stdin); // free: release memory. //free(Debug); // delete: C++ release memory. delete [] Debug; system("PAUSE"); }
Yahoo! Answers Visit the source
Other answers
I don't even get what kind of validation you're trying to buy there. The code does not do any more work than just: int Input=0; printf("Enter an integer value:"); /* Request input */ scanf("%d",&Input);
I write in c++, and I’m just beginning so I am no expert, but why did you create a pointer and store a number? Also, you can test whether the next char is a character by using isalpha(yourVariable). To separate a number 1 digit at a time you can use the modulus % which will return the remainder and then once you have tested that use the divisor (assumes you are using int variables, the divisor operator acts differently /w float or double) to shorten your number by 1. Anyway, not sure if I addressed your Q, but I hope so.
I hear what you're saying about the need for input validation, but you have to be careful with statements like "There's just no way to check if a user actually entered a character.". There is indeed a way to check, and validating integer input in C is not as difficult or convoluted as you're making it. I agree with Nick that your code is suspect. Here is a simple way to do it: #include <stdio.h> #define MAX_LINE_LEN 256 typedef enum { false = 0, true } bool; int getInt(); int main(int argc, char *argv[]) { while (1) { printf("> "); printf("%d\n",getInt()); } return 0; } int getInt() { bool inputOk; static char line[MAX_LINE_LEN]; static char junk[MAX_LINE_LEN]; int z; for (inputOk = false; inputOk == false; ) { fgets(line,MAX_LINE_LEN,stdin); inputOk = (sscanf(line,"%d%s",&z,junk) == 1); if (inputOk == false) { printf("invalid input, try again: "); } } return z; } #if 0 Sample run: > 22 22 > x invalid input, try again: 10 20 invalid input, try again: 10 10 > 99z invalid input, try again: 99 99 > -10 -10 > - 20 invalid input, try again: 0 0 > #endif
I don't understand your comment concerning using functions from ctypes.h not working in an if. care to elaborate? Your code shouldn't even compile Getstrlen is not a standard C library function, so I am not sure what compiler you are using. malloc returns a void pointer, it will always need casting to a type. Moving on to the actual code it doesn't work. Your code would only work for the values 49, 50, 51, 52, 53, 54, 55, 56 and 57 which are the ASCII values for characters 1 thru 9. Any other value will fail. You even managed to miss out zero in the numeric entry as it is. You would be better off reading input as a string and then validating it character by character, reading it as an integer means that fscanf will already be converted to an integer where possible, conversion aborts at the first nonnumeric character so entering "123a" will result in 123.
Related Q & A:
- Can someone help me find a study abroad program?Best solution by Yahoo! Answers
- Can someone help me with my psp warranty?Best solution by Yahoo! Answers
- Can someone help me locate an orphanage in Israel?Best solution by Yahoo! Answers
- Can someone help me find the phone number of the Consulate of Honduras in Houston, Texas?Best solution by Yahoo! Answers
- Can someone help with the MSN messenger?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.