You are on page 1of 3
Basics of Formatted Input/Output in C Concepts + 10 is essentially done one characte (or byte) at time stream ~ & sequence of characters owing fram one place to another © input stream: dala flows from input device (keyboar, fle, ee) into memory © output stream: date flows trom memory to output device (moniter, file, printer, et) ‘+ Standard VO streams (with builtin meaning) © stdin: standard input steam (def is keyboard) © stdout: standard output sream (defaults t0 monitor) © stderr: standard eror stream + staio.n~ contains basic VO functions scant: reads fom standard inp (ste) © printf: writes ta standard output (stout) © There are ater factions simiat to printf and scan that write to and read fom other streams © How fe include, for Cor C1 compiler ‘inelude U1 fon 3 Gos compiler ‘+ Formatted VO ~ refers tothe conversion of data fo and from a steam of characters, fr printing (or reading) in plain text format © All text UO we do is considered formatted 10 © The other option is reading/oriing direct binary information (common with fle VO, for example) Recap + The basic format ofa printf function calli print? (format string, List_of_expressions); where: © format_strng isthe layout of wha’ being printed © list.of expressions iss comma-separated list of variables or expressions yielding results tobe inserted int the output + To output string tras, just use one parameter on printf, the string itself print#(“Hello, wortd\n"); Drint (erect ings, arch ine\n\n"); Conversion Specifiers A conversion spevifir i a symbol that is used as a placeholder ina formating string, For integer output (for example), 2 is the specifier that holds the place for integers Here are some commonly used conversion specifier (not 2 comprehensive list) Xe ne (Signed decinaltrteger) Ae Unsigned decinol integer Xf floating point values: (45x04 notation) ~ float, double Xe Floating point values (oxporential notation} ke String Be Gharacter Printing Integers ‘+ To output an integer, use xin the format string, and an integer expression in the list_of expressions. sr nunstudents = 351235 Drinte(*FSu has 34 students", nunstudents); 17 output: 11 FSU has 35323 students + We can specify the feld with (i.e, how many spaces the item prints in). Defaults rightustificaion Place a number Between the Xand the dn this, ‘example, Geld width is 10: Print ¢(“FSU has 10d students”, morstudents); 17 ostput: U1 fsuhas 35123 students + To let justify, use @ negative number in the field width printe(“FSu has 10d students", murstudents); 11 Output: U1 #3U"hss 35123 students + he fed width is too small or Left unspecified, it defaults to the minirmum numberof characters required to print the item: print¢(*FSU has Kad students", unstudents); cutie nosy ohn ts 11 oatput: 11 P3U hae 39123 students ‘+ Specifying the field width is most useful when printing multiple fines of output that are meant 1o line up ina table format Printing Floating-point numbers + Use the x modiferto print floating point values in fixed notation print*("Your total £5 $8¢ today\n", cost); 17 ostput: U1 Youn tora) 45 $123, 456000 today + Use xe for exponential notation: print ¢("Your total 4s Ste tofay\n", cost); Hf output: U1 Mou torah 4s $1.2345006+02 today [Note that the e+02 means "times 10 to the 2nd power” ‘+ You canals control the decimal precision, which isthe numberof places after the decimal. Output will rund tothe appropriate numberof decimal places, if necessary: print¢(*Your total 4s $8.26 soday\n", cost)s 47 oatpur: Ui Your total $s $123.45 toeay + Field widh can also be controlled, as with integers: print#("Your total £6 $29.26 today\a", cost); 11 ostout 11 Youn toral is $ 123.65 today Inthe conversion specifier, the number before the decimal efcld width, and the number aftr is the precision (In this example, 9 and 2), © X-9.2 would left jutify in fcld width of 9, s with integers Printing characters and strings ‘+ Use the formatting specifier efor characters. Default fel size is 1 character: char letter = Qs prince(ietcke\n, “*, detter, ye 11 output ts: 1 + Uses for prising strings, Field widths work ust ike with integers print¢("AsRtest-1@sevo\n", “Hello, "ALICE", “Bos"): 11 tout: Wi wello Alicetob eNO ‘ouput. contains al ofthe above sample outputs. Try running t yourself seanf Basics sn fantion, The base form ofa call to scan i + To read dats in fom standard input (keyboard), we ell hes scan¢(format_string, List of vartobte addresses); © The forma string is like that of printf © But instead of expressions, we need space to store incoming data, hence the list of variable addresses + xis a variable, then the expression ax means Yaddcess of x * scanf example: Ant month, days print(*Please enten your birth noth, folloved by the day Seane("xa ta", ont 8439); + Conversion Specitiers ‘© Mostly the same as for output, Some small differences © Use ¢ for type Fst, bul use X¢ for types double and Jong double + The datatype read, the conversion specifier, andthe variable sed need to match in type {White space is skipped by default in consccutve numeric reeds, But its not skipped fr charactrltring inp Example input. linked here include nt main() utinata nearer ohn ‘ aot oat’ che printe(“Enter_an integer ana Seanfxenricry ly Wty 82); ‘ftoat, then ¥ oF KD “5 princé(-You entered:\n"): printe("r = Say f= Ms C= Belay Ls Fy Os > Sample run #1 User input underlined, to distinguish it from program output knter an snteger and 2 float, ten ¥ oF W ‘ou enter: PE eS ae.see, «= [Note that inthis sample run, the character tht was rad was NOTT the lettr'N’ twas the space. (Remember, white space not skipped on character reed). ‘This can be accounted for. Consider if the scan line looked like this seanf("ROKE He", A, HF, 8); ‘heres a space betwen the and thee inthe format sting. This allows the user to type a space. Suppose ths isthe typed inp: “Then the character variable ¢ will now contain the 'N inpui2.¢~ a version ofthe example with tis change is linked here Interactive Input ‘You can make input more interactive by prompting the user more carefully. This canbe tedious in some places, but in many occasions, it makes programs more user-friendly. Example: printe(*please enter your age: “); Seane(o", tage): printe(*pleese enter your gpa: “Ys Seane(omie", Maza), printt(*3o jou like pie (¥/N)? “Ds Seane(xe", Ranswer) ‘A good way to learn more about scan¢ isto try various inputs in various combinations, and type in test cases ~ see what happens! printf/scanf with C-strings ‘An entire C-tyle string can be easly printed, by using the %s formating symbol, along withthe name of the char array storing the string (asthe argument filing in that poston) char greeting{) = “ieLLo"; printe("Xs", greeting); 17 prints the word "Hetto" [Be careful o only use this on char strays that are being used as style stings. (Ths means, ony ithe null character i present asa terminator) ‘Simileny, you can read a sting int a char array with scané. The following cal allows de entry of @ word (upto 19 characters and a terminating mul character) from the keyboard, which is stored in the array word char wore [2015 (Characters are read from the keyboard until the frst "white space” (space, tab, newline) characteris encountered. The inputs stored in the character arrgy and ‘he null characteris automaticaly appended. Note also thatthe & was not needed inthe sean call (grat was used, instead of tuord), This is because the name ofthe array by itself (With no index) actually IS. variable that stores an address (a pointer. cutie nosy ohn ss

You might also like