240-491 Adv. UNIX:io/9 Advanced UNIX Advanced UNIX Objectives of these slides: Objectives of these slides: – look in some detail at standard look in some detail at standard input input and output in C and output in C 240-491 Special Topics in Comp. Eng. 1 Semester 2, 2000-2001 9. Standard I/O in C
39
Embed
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.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
240-491 Adv. UNIX:io/9 1
Advanced UNIXAdvanced UNIX
Objectives of these slides:Objectives of these slides:– look in some detail at standard input look in some detail at standard input
and output in Cand output in C
240-491 Special Topics in Comp. Eng. 1Semester 2, 2000-2001
char name[SIZE], ch;char name[SIZE], ch; : :printf(“Hi, there, %s\n”, name);printf(“Hi, there, %s\n”, name);printf(“The letter is printf(“The letter is %c%c \n”, ch); \n”, ch);
See man ascii for some unusual chars, e.g. '\a' '\b' '\r'
240-491 Adv. UNIX:io/9 6
Less Used printf() Format SpecifiersLess Used printf() Format Specifiers
SpecifierSpecifier MeaningMeaning%%%% % character% character%u%u Decimal unsigned integerDecimal unsigned integer%o%o Octal integerOctal integer%x%x Hexadecimal integerHexadecimal integer%p%p Pointer (decimal or hex)Pointer (decimal or hex)%n%n Store the number of charsStore the number of chars
written so farwritten so far
continued
useful forprintingunusualchars, seeman ascii
240-491 Adv. UNIX:io/9 7
ExamplesExamples
int i = 125, num;int i = 125, num;int *p = &i;int *p = &i;
printf(“%d, printf(“%d, %o, %x, %X, %p%n%o, %x, %X, %p%n\n”,\n”,i, i, i, i, p, &num);i, i, i, i, p, &num);
Specify minimum number of characters printed:Specify minimum number of characters printed:– if too few characters, right justify outputif too few characters, right justify output
– if too many, ignore field widthif too many, ignore field width
2.3. Precision (.) in printf()2.3. Precision (.) in printf()
SpecifierSpecifier EffectEffect%d%d Min. no. of digits Min. no. of digits
(pad with leading zeros)(pad with leading zeros)
%e, %f%e, %f No. of digits after the decimal pointNo. of digits after the decimal point
%g%g No. of significant digitsNo. of significant digits
%s%s Min. no. of characters from a stringMin. no. of characters from a string
240-491 Adv. UNIX:io/9 17
ExampleExample
int i = 873;int i = 873;float f = 123.94536;float f = 123.94536;char s[] = “Happy Birthday”;char s[] = “Happy Birthday”;printf(“%printf(“%.4d.4d\n%.9d\n”, i, i);\n%.9d\n”, i, i);printf(“%printf(“%.3f.3f\n%\n%.3e.3e\n%\n%.3g.3g\n”, f, f, f);\n”, f, f, f);printf(“%printf(“%.11s.11s\n”, s);\n”, s);
Place h or l before d, o, x, or uPlace h or l before d, o, x, or u
Place L before e, f, or gPlace L before e, f, or g
LetterLetter EffectEffecthh Specify Specify shortshort typetypell Specify Specify longlong type typeL L Specify Specify long doublelong double type type
NotesNotes %d%d will read a sign (e.g. will read a sign (e.g. -27-27))
%f%f will accept a float in fractional or will accept a float in fractional or exponential form (e.g. exponential form (e.g. 2.32.3, , 1.2e+021.2e+02) )
scanf()scanf() will ignore whitespace to get to will ignore whitespace to get to a numbera number– scanf("%d", &x);scanf("%d", &x);
– whitespace includes new lineswhitespace includes new lines
continued
-27
240-491 Adv. UNIX:io/9 22
%s%s only reads non-whitespace characters only reads non-whitespace characters– scanf("%s %s", str1, str2);scanf("%s %s", str1, str2);
– skips whitespace to start of textskips whitespace to start of text– stops reading in text when it gets to a whitespacestops reading in text when it gets to a whitespace– adds ‘\0’adds ‘\0’– the string variable (e.g. the string variable (e.g. str1str1) must have enough memory) must have enough memory
continued
hello andy
240-491 Adv. UNIX:io/9 23
scanf("%d%d", &x, &y);scanf("%d%d", &x, &y);
same assame as scanf(“%d”, &x);scanf(“%d”, &x);scanf(“%d”, &y);scanf(“%d”, &y);
scanf()scanf() will read will read xx and and yy values from the values from the same line, or any distance apart, so long as same line, or any distance apart, so long as the values are separated by whitespace.the values are separated by whitespace.
continued
27 13
240-491 Adv. UNIX:io/9 24
%c%c will read any character (even will read any character (even whitespace):whitespace):scanf(“%c”, &ch);scanf(“%c”, &ch);
Other characters in the Other characters in the scanf()scanf() format format string are used for input matching:string are used for input matching:scanf(“%d-%d %d”, &x, &y, &z);scanf(“%d-%d %d”, &x, &y, &z);
continued
27-13 5
240-491 Adv. UNIX:io/9 25
scanf()scanf() leaves non-matching characters leaves non-matching characters on the input streamon the input stream
printf(“Enter date as mm-dd-yy: “);printf(“Enter date as mm-dd-yy: “);scanf(“%dscanf(“%d%*c%*c%d%d%*c%*c%d”, &month, %d”, &month,
&day, &year);&day, &year);printf(“month = %d day = %d year = %d\n”, printf(“month = %d day = %d year = %d\n”,
month, day, year);month, day, year);
Enter date as mm-dd-yy: Enter date as mm-dd-yy: 11-18_9711-18_97month = 11 day = 18 year = 97month = 11 day = 18 year = 97
240-491 Adv. UNIX:io/9 28
3.2. Field Widths3.2. Field Widths
A field width specifies the maximum number of A field width specifies the maximum number of input characters to process (ignoring whitespace input characters to process (ignoring whitespace before the start).before the start).
– scanf()scanf() returns when it sees a character returns when it sees a character that it does not want. It leaves the that it does not want. It leaves the character on the input stream;character on the input stream;
– scanf()scanf() returns the number of returns the number of variables it has boundvariables it has bound
continued
240-491 Adv. UNIX:io/9 32
/* Try to read two integers *//* Try to read two integers */#include <stdio.h>#include <stdio.h>
int main()int main(){ int i, j, count;{ int i, j, count; do { do { printf(“Enter two integers: “); printf(“Enter two integers: “); count = scanf(“%d %d, &i, &j)count = scanf(“%d %d, &i, &j);; if (count < 2) { if (count < 2) { /* somthing wrong *//* somthing wrong */ scanf(“ scanf(“%*[^\n]%*[^\n]”);”); /* skip to end of line *//* skip to end of line */ printf(“Incorrect. Try again: “); printf(“Incorrect. Try again: “); } } } while (count < 2); } while (count < 2); /* until valid input *//* until valid input */ : :}}
– e.g. e.g. puts(“Hello World”);puts(“Hello World”);
– Adds a newline to its output.Adds a newline to its output.
– If there is an error it returns If there is an error it returns EOFEOF; ; If okay it returns a non-negative integer.If okay it returns a non-negative integer.
240-491 Adv. UNIX:io/9 34
char *gets(char *line);char *gets(char *line);
– e.g: e.g: gets(str);gets(str);
– Reads to a newline in Reads to a newline in stdinstdin; ; replaces newlinereplaces newline by by ‘\0’‘\0’ in input argument in input argument
– gets()gets() returns a returns a NULLNULL when when EOFEOF or an error occurs. or an error occurs.
– Main problemMain problem: : gets()gets() may read in a bigger string may read in a bigger string than can be stored in the variable; than can be stored in the variable; use use fgets()fgets() instead. instead.
Bad style:avoid gets()
240-491 Adv. UNIX:io/9 35
char *fgets(char *line, int n,char *fgets(char *line, int n,FILE *stream);FILE *stream);
– Reads at most Reads at most n-1n-1 chars into chars into lineline, stopping if a newline is , stopping if a newline is encountered;encountered;
– the the newline is includednewline is included in in lineline, and a , and a ‘\0’‘\0’ is added is added
– fgets()fgets() returns a returns a NULLNULL when when EOFEOF or an error occurs. or an error occurs.
240-491 Adv. UNIX:io/9 36
sscanf()sscanf()
int sscanf(char *s, int sscanf(char *s, const char *format, ...);const char *format, ...);
Same as Same as scanf()scanf() but its input comes from but its input comes from the string argument (the string argument (ss) not from ) not from stdinstdin..
Very useful for separatingreading from processingin code.
240-491 Adv. UNIX:io/9 37
Read Read thenthen Process Process
#include <stdio.h>#include <stdio.h>int main()int main(){ char str[120]; /* magic number: poor style! */{ char str[120]; /* magic number: poor style! */ int i, j; int i, j; while (fgets(str,120,stdin) != NULL) { /* read */ while (fgets(str,120,stdin) != NULL) { /* read */
/* process *//* process */ if ( if (sscanf(str, “%d %d”, &i, &j) == 2sscanf(str, “%d %d”, &i, &j) == 2) ) printf(“i = %d j = %d\n”, i, j); printf(“i = %d j = %d\n”, i, j); else if ( else if (sscanf(str, “%d”, &i) == 1sscanf(str, “%d”, &i) == 1)) printf(“i = %d j = ??\n”, i); printf(“i = %d j = ??\n”, i); else else printf(“Could not understand anything!\n”); printf(“Could not understand anything!\n”); : :}}
printf(“Press any key to go on...”); printf(“Press any key to go on...”); ch = getchar(); /* type conversion */ ch = getchar(); /* type conversion */ printf(“You pressed ‘%c’\n”, ch); printf(“You pressed ‘%c’\n”, ch); : :}}
ProblemProblem: UNIX line buffering: UNIX line buffering Quick fixQuick fix: say : say “Press RETURN”“Press RETURN”