1 / 6

IO revisited

IO revisited. stdio.h. Functions printf scanf (normally stops at whitespace) fgets sscanf Standard streams stdin (defaults to keyboard) stdout (defaults to console) stderr (defaults to console). scanf and incorrect input. scanf input is based on pattern matching

courtney
Download Presentation

IO revisited

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. IO revisited

  2. stdio.h • Functions • printf • scanf (normally stops at whitespace) • fgets • sscanf • Standard streams • stdin (defaults to keyboard) • stdout (defaults to console) • stderr (defaults to console)

  3. scanf and incorrect input • scanf input is based on pattern matching • If incorrect input is entered, the pattern is not matched and the input characters remain in the buffer

  4. fgets – get string from stream • char *fgets(char *s, int size, FILE *stream); • Read in size - 1 characters from the stream and stores it into *s pointer. • The string is automatically null-terminated. • fgets stops reading in characters if it reaches an EOF or newline. • Ex: char s[100]; fgets(s, sizeof(s), stdin); // read a line from stdin

  5. sscanf– read formatted data from string • intsscanf(const char *str, const char *format, ...); • *str is a string / character array / pointer to character • *format is a string literal • Additional arguments are pointers to the types in *format • Ex: #include <stdio.h> #include <stdlib.h> int main() { int day, year; char weekday[20], month[20], dtm[100]; strcpy( dtm, "Saturday March 25 1989" ); sscanf( dtm, "%s %s %d %d", weekday, month, &day, &year ); printf("%s %d, %d = %s\n", month, day, year, weekday ); return(0); } Output: March 25, 1989 = Saturday

  6. IO redirection • When running an executable > redirects output < redirects input | pipe (stdout from one program to stdinof another) Examples: testprog > fileout (output of testprog goes to fileout) testprog < filein (input of testprog comes from filein) prog1 | prog2 (input of prog2 comes from output of prog1)

More Related