Getting user input|
OK, so far you know how to define variables, and print them to the screen using 'printf' Now comes the next step in interacting with the user. scanf. Scanf is basically the opposite to printf. Instead of writing text to the screen, it reads the user input, and then puts the info into a variable, so you can then easily manipulate it. As always, i'll show you with an example:
/* tutorial 5 - User Input Example - userin.c */
Not to difficult I think. The first printf would write "What number would you like to display?". Note that after the question mark, there is a space, and no \n. All this does is leave the cursor on the same line, with a space after the question mark, so the users input would appear on the same line. After this, the program will wait for the user to insert number, and press enter, signifying the program can continue. The input is then stuffed in the variable test.
One important thing to note is that the variable name inside scanf must have an '&' symbol in front of it. In C, & followed by a variable name refers to the address of that variable in the memory, e.g. &test is the address of variable test. Its kind of weird, but don't worry about that now, we'll get into that later:)
printf("What number would you like to display? ");
printf("\nThe number you typed was %d.\n", test);
The scanf("%d", &test) statment reads the input from the keyboard as a decimal number, and assigns that value to variable test.
Now, with this information, lets try and write something useful! We'll try getting input of a different type too. This small utility will let you find the ASCII value of any character. It's pretty easy, so lets take a look:
/* Tutorial 5 - ASCII chart - ASCCHRT.C */
There...I don't think this program needs much explanation. It just gets the value from the user, prints it out once as a character, and then as a decimal number, giving its ASCII value!
printf("\nWhat character do you want the ASCII value of > ");
printf("The ASCII value of %c is %d \n", ChrVal, ChrVal);
Tutorial by Puke