Download presentation
Presentation is loading. Please wait.
Published byLiliana McBride Modified over 9 years ago
1
240-491 Adv. UNIX:io/91 Advanced UNIX v Objectives of these slides: –look in some detail at standard input and output in C 240-491 Special Topics in Comp. Eng. 1 Semester 2, 2000-2001 9. Standard I/O in C
2
240-491 Adv. UNIX:io/92 Overview 1. Background 2. Formatted Output: printf() 3. Formatted Input: scanf() 4. Line I/O: gets(), puts() 5. Character I/O: getchar(), putchar()
3
240-491 Adv. UNIX:io/93 1. Background Most I/O library functions are in stdio.h v Basic methods: –1. Formatted I/O –2. Line by line –3. Character by character
4
240-491 Adv. UNIX:io/94 2. Formatted Output: printf() int i = 2, j = 7; printf(“i = %d, j = %d\n”, i, j); float, double printed with %f, %e, %g : double x = 3.14; printf(“%f, %e, %g\n”, x, x, x); 3.140000, 3.140000e+00, 3.14 6 dp is the default
5
240-491 Adv. UNIX:io/95 Character Strings v char name[SIZE], ch; : printf(“Hi, there, %s\n”, name); printf(“The letter is %c \n”, ch); See man ascii for some unusual chars, e.g. ' \a' '\b' '\r'
6
240-491 Adv. UNIX:io/96 Less Used printf() Format Specifiers v SpecifierMeaning %% character %uDecimal unsigned integer %oOctal integer %xHexadecimal integer %pPointer (decimal or hex) %nStore the number of chars written so far continued useful for printing unusual chars, see man ascii
7
240-491 Adv. UNIX:io/97 Examples v int i = 125, num; int *p = &i; printf(“%d, %o, %x, %X, %p%n\n”, i, i, i, i, p, &num); printf(“num = %d\n”, num); 125, 175, 7d, 7D, 7fffbe48 num = 31 upper case hex letters the decimal is converted
8
240-491 Adv. UNIX:io/98 Four Types of Format Modifiers 1. Flags –e.g. "%+d" 2. Field Widths –e.g. "%10d" 3. Precision –e.g. "%.4d" 4. Type Modifiers –e.g. "%ld" printf(".....", x, y, z); format string
9
240-491 Adv. UNIX:io/99 2.1. Flags v FlagMeaning +Prefix positive numbers with a + sign spacePrefix positive numbers with a space 0Pad with leading zeros #Alternate output form
10
240-491 Adv. UNIX:io/910 Examples printf(“%+d\n%+d\n”, 786, -786); +786 -786 printf(“% d\n% d\n”, 547, -547); 547 -547 v printf(“%+09d\n%09d\n”, 452, 452); +00000452 000000452 useful for tidy columns
11
240-491 Adv. UNIX:io/911 Meaning of # Prefix 0 is added to octal output ( %#o ). Prefix 0x or 0X is added to hexadecimal output ( %#x or %#X ). %#e, %#f, %#g have a decimal point, even when there are no digits after it. %#g does not remove trailing zeros.
12
240-491 Adv. UNIX:io/912 v int c = 1427; float p = 1427.0; printf(“%#o, %#x, %#X, %g, %#g\n”, c, c, c, p, p); 02623, 0x593, 0X593, 1427, 1427.00 # Examples octalhex remove '.' and 0's do not remove '.' and 0's
13
240-491 Adv. UNIX:io/913 2.2. Field Widths v Specify minimum number of characters printed: –if too few characters, right justify output –if too many, ignore field width
14
240-491 Adv. UNIX:io/914 Example char *s = “hello”; int x = 23; printf(“%10d%10s\n”, x, s); printf(“%-10d%-10s\n”, x, s); 23 hello 23 hello width - = left justify 10
15
240-491 Adv. UNIX:io/915 Field Width (*) in printf() Calculate field width based on the next printf() argument: #define FIELD_WIDTH 10 printf(“%*d\n”, FIELD_WIDTH, val); uses FIELD_WIDTH
16
240-491 Adv. UNIX:io/916 2.3. Precision (.) in printf() v SpecifierEffect %dMin. no. of digits (pad with leading zeros) %e, %fNo. of digits after the decimal point %gNo. of significant digits %sMin. no. of characters from a string
17
240-491 Adv. UNIX:io/917 Example int i = 873; float f = 123.94536; char s[] = “Happy Birthday”; printf(“%.4d\n%.9d\n”, i, i); printf(“%.3f\n%.3e\n%.3g\n”, f, f, f); printf(“%.11s\n”, s); 0873 000000873 123.945 1.293e+02 124 Happy Birth
18
240-491 Adv. UNIX:io/918 Meaning of *.* Calculate field width and precision from the next arguments of the printf() printf(“%*.*s\n”, field_width, precision, str);
19
240-491 Adv. UNIX:io/919 2.4. Type Modifiers v Place h or l before d, o, x, or u v Place L before e, f, or g LetterEffect hSpecify short type lSpecify long type L Specify long double type
20
240-491 Adv. UNIX:io/920 3. Formatted Input: scanf() v int i, x, y; float val; char str[100]; scanf(“%d”, &i); /* read in integer */ scanf(“%f”, &val); /* read in float */ scanf(“%s”, str); /* read in string */ scanf(“%d%d”, &x, &y); /* read space-separated integers */ 23 2.3 hi -5 62
21
240-491 Adv. UNIX:io/921 Notes %d will read a sign (e.g. -27 ) %f will accept a float in fractional or exponential form (e.g. 2.3, 1.2e+02 ) scanf() will ignore whitespace to get to a number –scanf("%d", &x); –whitespace includes new lines continued -27
22
240-491 Adv. UNIX:io/922 %s only reads non-whitespace characters –scanf("%s %s", str1, str2); –skips whitespace to start of text –stops reading in text when it gets to a whitespace –adds ‘\0’ –the string variable (e.g. str1 ) must have enough memory continued hello andy
23
240-491 Adv. UNIX:io/923 v scanf("%d%d", &x, &y); same as scanf(“%d”, &x); scanf(“%d”, &y); scanf() will read x and y values from the same line, or any distance apart, so long as the values are separated by whitespace. continued 27 13
24
240-491 Adv. UNIX:io/924 %c will read any character (even whitespace): scanf(“%c”, &ch); Other characters in the scanf() format string are used for input matching: scanf(“%d-%d %d”, &x, &y, &z); continued 27-13 5
25
240-491 Adv. UNIX:io/925 scanf() leaves non-matching characters on the input stream scanf("%d", &x); scanf("%s", str); scanf() returns the number of bound variables, or EOF at end-of-file. int num; num = scanf("%d %d", &x, &y); hello 27 13 continued
26
240-491 Adv. UNIX:io/926 scanf() uses line buffering –when scanf() is reading from the keyboard, it only gets a line to process when a RETURN is pressed
27
240-491 Adv. UNIX:io/927 3.1. Assignment Supression (*) int month, day, year; printf(“Enter date as mm-dd-yy: “); scanf(“%d%*c%d%*c%d”, &month, &day, &year); printf(“month = %d day = %d year = %d\n”, month, day, year); Enter date as mm-dd-yy: 11-18_97 month = 11 day = 18 year = 97
28
240-491 Adv. UNIX:io/928 3.2. Field Widths v A field width specifies the maximum number of input characters to process (ignoring whitespace before the start). v int x, y; scanf(“%2d%d”, &x, &y); printf(“Integers are: %d, %d\n”, x, y); 123456 Integers are: 12, 3456
29
240-491 Adv. UNIX:io/929 3.3. Scan Sets [...] v Specify characters that can be read. v char z[9]; printf(“Enter String: “); scanf(“%[aeiou]”, z); printf(“The input was \”%s\”\n”, z); Enter String: ooeeooahah The input was “ooeeooa”
30
240-491 Adv. UNIX:io/930 Inverted Scan Sets [^...] v Specify characters not to be read. v char z[9]; printf(“Enter String: “); scanf(“%[^aeiou]”, z); printf(“The input was \”%s\”\n”, z); Enter String: Phreak The input was “Phr”
31
240-491 Adv. UNIX:io/931 3.4. Handling Incorrect Input v Things to remember: –scanf() returns when it sees a character that it does not want. It leaves the character on the input stream; –scanf() returns the number of variables it has bound continued
32
240-491 Adv. UNIX:io/932 /* Try to read two integers */ #include int main() { int i, j, count; do { printf(“Enter two integers: “); count = scanf(“%d %d, &i, &j); if (count int main() { int i, j, count; do { printf(“Enter two integers: “); count = scanf(“%d %d, &i, &j); if (count < 2) {/* somthing wrong */ scanf(“%*[^\n]”);/* skip to end of line */ printf(“Incorrect. Try again: “); } } while (count < 2);/* until valid input */ : } * supresses assign; [^\n] matches upto newline (whitespace)
33
240-491 Adv. UNIX:io/933 4. Line I/O int puts(char *line); –e.g. puts(“Hello World”); –Adds a newline to its output. –If there is an error it returns EOF ; If okay it returns a non-negative integer.
34
240-491 Adv. UNIX:io/934 char *gets(char *line); –e.g: gets(str); –Reads to a newline in stdin ; replaces newline by ‘\0’ in input argument –gets() returns a NULL when EOF or an error occurs. –Main problem: gets() may read in a bigger string than can be stored in the variable; use fgets() instead. Bad style: avoid gets()
35
240-491 Adv. UNIX:io/935 char *fgets(char *line, int n, FILE *stream); –e.g: fgets(str, 80, stdin); –Reads at most n-1 chars into line, stopping if a newline is encountered; –the newline is included in line, and a ‘\0’ is added –fgets() returns a NULL when EOF or an error occurs.
36
240-491 Adv. UNIX:io/936 sscanf() int sscanf(char *s, const char *format,...); Same as scanf() but its input comes from the string argument ( s ) not from stdin. Very useful for separating reading from processing in code.
37
240-491 Adv. UNIX:io/937 Read then Process v #include int main() { char str[120]; /* magic number: poor style! */ int i, j; while (fgets(str,120,stdin) != NULL) { /* read */ /* process */ if (sscanf(str, “%d %d”, &i, &j) == 2) printf(“i = %d j = %d\n”, i, j); else if (sscanf(str, “%d”, &i) == 1) printf(“i = %d j = ??\n”, i); else printf(“Could not understand anything!\n”); : }
38
240-491 Adv. UNIX:io/938 5. Character I/O v int putchar(int c); –e.g.: putchar(‘\n’); putchar(32); v int getchar(void); –e.g.: int ch; ch = getchar(); while ((ch = getchar()) != EOF)... Remember the brackets.
39
240-491 Adv. UNIX:io/939 Cannot “Press any key” #include int main() { char ch; printf(“Press any key to go on...”); ch = getchar(); /* type conversion */ printf(“You pressed ‘%c’\n”, ch); : } v Problem: UNIX line buffering Quick fix: say “Press RETURN”
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.