getchar vs scanf
Table of Contents
C Programming Help
Intro
- Hey Nick, hope your not too busy.
- I know its been a while but i finally got time to start catching up with C.
- I have a couple of problems to do and I need help to understand them
- I have two questions so far:
(1) getchar Vs scanf
Question
- What does getchar() do? is it like a scanf()?
General Information
- stdin
- first thing you need to have at least a basic grasp of is stdin (standard input)
- consider it to be a "stream" of characters, spaces, numbers, etc
- as if you took all the sentences in a book and made them one long line
- stdin is generally something the user is typing on a keyboard
- in order for your program to use stdin you need to tell the program how to read it and what to expect
- scanf
- scanf is most likely what you are going to use for all basic programs
- its an ugly, unsafe function, but it works well and is the easiest to explain.
- CPlusPlus - Scanf
- so scanf is one of those ways to read stdin AND tell the program what to expect
- you can see in the CPlusPlus link that you specify what to read (a character, string (word), decimal number, integer number)
- scanf is most likely what you are going to use for all basic programs
- getcharAs answered in the stackoverflow question getc Vs getchar Vs Scanf for reading a character from stdin
If you simply want to read a single character from stdin, then getchar() is the appropriate choice. If you have more complicated requirements, then getchar() won't be sufficient. getc() allows you to read from a different stream (say, one opened with fopen()); scanf() allows you to read more than just a single character at a time. The most common error when using getchar() is to try and use a char variable to store the result. You need to use an int variable, since the range of values getchar() returns is "a value in the range of unsigned char, plus the single negative value EOF". A char variable doesn't have sufficient range for this, which can mean that you can confuse a completely valid character return with EOF. The same applies to getc().
- so store the input obtained from getchar as an int (confusing I know)
int num = getchar(); //CORRECT char num = getchar(); //INCORRECT
- so store the input obtained from getchar as an int (confusing I know)
Code Demonstrations and Examples
- (1) scanf Number Correct Usage
- Code
#include<stdio.h> //don't forget header in order to use standard input and output int main(){ ////////////////////////////////////////////////////////////////////////////// // --------------------------------------------------------------------------- // -- Example 1 - Read a Number Normally with scanf // --------------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////////// printf("---------- Starting Example 1 ----------\n"); printf("-- Read a Number Normally with scanf --\n\n"); // ------------------------------------- // -- Variables // ------------------------------------- int good_number; // ------------------------------------- // -- Input // ------------------------------------- printf("Enter a Number, then hit Enter: "); scanf("%d", &good_number); //this will read a number printf("\t(read as a number using scanf)\n"); // ------------------------------------- // -- Output // ------------------------------------- printf("\nYou Entered: %d \n",good_number); printf("55 + %d = %d \t(Correct Math, What You Want)\n",good_number, 55 + good_number); // ------------------------------------- // -- Exit Program // ------------------------------------- printf("\n---------- Exiting Example 1 ----------\n"); return 0; }
- Results
- I typed: 88 <RETURN>
-——— Starting Example 1 ---------- – Read a Number Normally with scanf -- Enter a Number, then hit Enter: 88 (read as a number using scanf) You Entered: 88 55 + 88 = 143 (Correct Math, What You Want) -——— Exiting Example 1 ----------
- Code
- (2) scanf Number Incorrect Usage (Doing Math on a Word)
- Code
#include<stdio.h> int main(){ ////////////////////////////////////////////////////////////////////////////// // --------------------------------------------------------------------------- // -- Example 2 - Incorectly Read A Number with scanf // --------------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////////// printf("---------- Starting Example 2 ----------\n"); printf("-- Incorectly Read A Number with scanf --\n\n"); // ------------------------------------- // -- Variables // ------------------------------------- //if you don't know what this means thats ok, its "advanced" a "C String" //just know its basically a word char funny_number[10]; int addme = 100; //the number you add // ------------------------------------- // -- Input // ------------------------------------- printf("Enter a Number (less than 9 digits), then hit Enter: "); scanf("%s",funny_number); //read the input like a word // ------------------------------------- // -- Output // ------------------------------------- printf("\nYou Entered the text: %s (output as string)\n",funny_number); printf("\nNow trying to add %d to your number.\n", addme); printf("%d + %d = %d \n",addme, funny_number, 55 + funny_number); printf("\nExplanation:\n"); printf(" + this is correct math, but not what you want\n"); printf(" + %d was added to the word %d not the number %s\n", addme, funny_number, funny_number); printf(" + the input was read as text (like a word), and you can't do math on a word\n"); // ------------------------------------- // -- Exit Program // ------------------------------------- printf("\n---------- Exiting Example 2 ----------\n"); return 0; }
- Errors Compiling
- this is an error in usage, but the program will compile since nothing is syntactically wrong
- these were the warnings my compiler gave me:
- (line numbers are off because of the way I write code makes them look different than you would expect)
ex2scanfincorrectnumber.c: In function ‘main’: ex2scanfincorrectnumber.c:30:3: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘char *’ ex2scanfincorrectnumber.c:30:3: warning: format ‘%d’ expects type ‘int’, but argument 4 has type ‘char *’ ex2scanfincorrectnumber.c:34:3: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘char *’
- basically saying (what this program is demonstrating), you are operating on a word like a number (generally not desired)
- Output
-——— Starting Example 2 ---------- – Incorectly Read A Number with scanf -- Enter a Number (less than 9 digits), then hit Enter: 7361980 You Entered the text: 7361980 (output as string) Now trying to add 100 to your number. 100 + -1076284030 = -1076283975 Explanation:
- this is correct math, but not what you want
- 100 was added to the word -1076284030 not the number 7361980
- the input was read as text (like a word), and you can't do math on a word
- Code
- (3) scanf Characters
- Code
#include<stdio.h> int main(){ ////////////////////////////////////////////////////////////////////////////// // --------------------------------------------------------------------------- // -- Example 3 - Using scanf // --------------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////////// printf("---------- Start Example 3 ----------\n"); printf("-- Using scanf --\n\n"); // ------------------------------------- // -- Variables // ------------------------------------- char good_number [100]; char foo_input = '1'; int counter = 0; // ------------------------------------- // -- Input // ------------------------------------- printf("Randomly type letters, numbers, and hit enter a few times.\n"); printf("Enter 0 to EXIT loop and see results.\n"); while(foo_input != '0'){ scanf("%c",&foo_input); //this will read a character) good_number[counter] = foo_input; counter++; } // ------------------------------------- // -- Output // ------------------------------------- printf("\n\nResults:\n"); int i = 0; for(i; i <counter; i++){ printf("%.2d = %c\n", i, good_number[i]); } // ------------------------------------- // -- Exit Program // ------------------------------------- printf("\n---------- Exiting Example 3 ----------\n"); return 0; }
- Results
-——— Start Example 3 ---------- – Using scanf -- Randomly type letters, numbers, and hit enter a few times. Enter 0 to EXIT loop and see results. uasdfk asd9 a78 a;hjdsaf ui;; q j w eje ., a;jsf 0 Results: 00 = u 01 = a 02 = s 03 = d 04 = f 05 = k 06 = 07 = a 08 = s 09 = d 10 = 9 11 = 12 = a 13 = 7 14 = 8 15 = 16 = a 17 = ; 18 = h 19 = j 20 = d 21 = s 22 = a 23 = f 24 = 25 = u 26 = i 27 = ; 28 = ; 29 = 30 = q 31 = 32 = j 33 = 34 = w 35 = 36 = e 37 = j 38 = e 39 = 40 = . 41 = , 42 = 43 = a 44 = ; 45 = j 46 = s 47 = f 48 = 49 = 50 = 0 -——— Exiting Example 3 ----------
- Code
- (4) getchar Characters
- Code
#include<stdio.h> int main(){ ////////////////////////////////////////////////////////////////////////////// // --------------------------------------------------------------------------- // -- Example 4 - Using getchar // --------------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////////// printf("\n---------- Start Example 4 ----------\n"); printf("-- Using getchar --\n\n"); // ------------------------------------- // -- Variables // ------------------------------------- char good_number [100]; int foo_input = 1; int counter = 0; // ------------------------------------- // -- Input // ------------------------------------- printf("Randomly type letters, numbers, and hit enter a few times.\n"); printf("Enter 0 EXIT and see results\n"); while(foo_input != '0'){ foo_input = getchar(); good_number[counter] = foo_input; counter++; } // ------------------------------------- // -- Output // ------------------------------------- printf("\n\nResults:\n"); int i = 0; printf("Individually you Entered:\n"); for(i; i <counter; i++){ printf(" %.2d = %c\n", i, good_number[i]); } // ------------------------------------- // -- Exit Program // ------------------------------------- printf("\n---------- Exiting Example 4 ----------\n"); return 0; }
- Results
-——— Start Example 4 ---------- – Using getchar -- Randomly type letters, numbers, and hit enter a few times. Enter 0 EXIT and see results uasdfk asd9 a78 a;hjdsaf ui;; q j w eje ., a;jsf 0 Results: Individually you Entered: 00 = u 01 = a 02 = s 03 = d 04 = f 05 = k 06 = 07 = a 08 = s 09 = d 10 = 9 11 = 12 = a 13 = 7 14 = 8 15 = 16 = a 17 = ; 18 = h 19 = j 20 = d 21 = s 22 = a 23 = f 24 = 25 = u 26 = i 27 = ; 28 = ; 29 = 30 = q 31 = 32 = j 33 = 34 = w 35 = 36 = e 37 = j 38 = e 39 = 40 = . 41 = , 42 = 43 = a 44 = ; 45 = j 46 = s 47 = f 48 = 49 = 50 = 0 -——— Exiting Example 4 ----------
- Code
Further Resources
There is generally tons of documentation like this on the web, but they are often difficult to use when learning, easier to use as reference. But the simple examples on those sites are your best friends.
- CPlusPlus is always a great reference
- Wikibooks - getchar
(2) Using Chars as Ints
Question
int freq[26]; c=getchar(); if(isalpha(c)) { freq[tolower(c)-'a'] -= 1; freq[tolower(c)-'a'-1]++; }
- What does 'a' mean? (just showing you the part i dont get)
- I know tolower means reduce to lowercase but i have to subtract 'a' from it, but I dont get it
Code
Part of learning how to program is learning how to learn how to program (sounds redudant, I know.)
- for me the easiest way to do that is to break everything down into small parts and work up
- int freq1;
- so "freq" is an array of no more than 26 integers (numbers)
- you reference a number by a position in the array
#include<stdio.h> //don't forget header in order to use standard input and output int main(){ int freq[26]; int i = 0; for(i; i<26;i++){ freq[i] = (26*i)/3; printf("Freq[%d] \t= (26*%d)/3 \t= %d\n", i, i, freq[i]); } return 0; }
- c=getchar();
- in this problem its actually very important to know what data type c is
- I am going to assume it is an int, since that is the proper usage of getchar
- You need to understand what c actually is
- Code
#include<stdio.h> //don't forget header in order to use standard input and output int main(){ ////////////////////////////////////////////////////////////////////////////// // --------------------------------------------------------------------------- // -- Characters as Integer Data // --------------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////////// printf("---------- Starting Program ----------\n"); printf("-- Characters as Integers --\n\n"); // ------------------------------------- // -- Input and Variables // ------------------------------------- printf("Enter a lower case letter (the letter c to compare), and hit ENTER: "); //IF you enter c, these two will be equivilant int user_data = getchar(); int hardcode = 'c'; // ------------------------------------- // -- Output // ------------------------------------- printf("\nResults:\n"); printf("|----------------|---------------|---------------|\n"); printf("| Value\t\t | User Input\t | Hardcoded c\t |\n"); printf("| Integer\t | \t %d \t | \t %d \t |\n", user_data, hardcode); printf("| Character\t | \t %c \t | \t %c \t |\n", user_data, hardcode); printf("|----------------|---------------|---------------|\n"); //Exit Program printf("\n---------- Exiting Program ----------\n"); return 0; }
- Output
-——— Starting Program ---------- – Characters as Integers -- Enter a lower case letter (the letter c to compare), and hit ENTER: c Results:
-——— Exiting Program ---------- Value User Input Hardcoded c Integer 99 99 Character c c
- Explanation
- notice the value 99, and compare it to ascii value 99
- you are actually storing the ascii value of the character as an integer
- when you display an integer as a character
- the character you see will actually be the corresponding ascii character
- Print All ASCII Characters
- here is a simple proof of printing ascii int value to char
- Code
#include<stdio.h> //don't forget header in order to use standard input and output int main(){ ////////////////////////////////////////////////////////////////////////////// // --------------------------------------------------------------------------- // -- Print ASCII // --------------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////////// printf("---------- Starting Program ----------\n"); printf("-- Print Ascii Characters --\n"); int i = 0; for(i; i<=127;i++){ printf("Ascii Value %d = %c\n",i,i); } printf("\n---------- Exiting Program ----------\n"); return 0; }
- Output
-——— Starting Program ---------- – Print Ascii Characters -- Ascii Value 0 =
- in this problem its actually very important to know what data type c is