Question:
C programming- Can someone help me understand my own solution?
?
2009-12-12 22:51:36 UTC
//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.
Six answers:
Nick T
2009-12-13 06:11:22 UTC
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.
cja
2009-12-14 09:49:57 UTC
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



#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
?
2009-12-12 23:08:54 UTC
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.
Lie Ryan
2009-12-13 16:54:58 UTC
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);
anonymous
2016-12-16 10:04:05 UTC
C++ would be a perplexing language to benefit. there is lots of up front getting to understand for regulations and header contains etc. i'd individually propose getting to understand a language the place you may get going quicker like C#, yet many CS human beings would disagree with me. i'd propose strolling nonetheless some "hi, international" type tutorials and then working my way as much as the extra progressed ones. which will frequently help you learn it quicker than purely interpreting the e book.
Big_John-tw
2009-12-13 22:08:27 UTC
include

#include

#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 = "<
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");

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...