1 / 57

C Standard Input and Output: printf and scanf

This tutorial explains the use of printf and scanf functions for input and output in C, with examples and explanations of conversion specifiers. It also covers string literals and variables.

Télécharger la présentation

C Standard Input and Output: printf and scanf

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. Input and Output in C

  2. Standard Input and Output • Output: printf • Input: scanf • Remember the program computing the distance between two points! • /* Declare and initialize variables. */ • double x1=1, y1=5, x2=4, y2=7, • side_1, side_2, distance; • How can we compute distance for different points? • It would be better to get new points from user, right? For this we will use scanf • To use these functions, we need to use #include <stdio.h>

  3. Standard Output • printf Function • prints information to the screen • requires two arguments • control string • Contains text, conversion specifiers or both • Identifier to be printed • Example double angle = 45.5; printf(“Angle = %.2f degrees \n”, angle); Output: Angle = 45.50 degrees Conversion Specifier Control String Identifier

  4. Conversion Specifiers for Output Statements Frequently Used

  5. Standard Input • scanf Function • inputs values from the keyboard • required arguments • control string • memory locations that correspond to the specifiers in the control string • Example: double distance; char unit_length; scanf("%lf %c", &distance, &unit_length); • It is very important to use a specifier that is appropriate for the data type of the variable

  6. Conversion Specifiers for Input Statements Frequently Used

  7. Arguments to main() int main(int argc, char *argv[]) { int i; printf("argc = %d\n",argc); for (i=0; i<argc; i++) printf("argv[%d] = %s\n",i,argv[i]); return 0; }

  8. Arguments to main() fox01> ./myprog this is apple argc = 4 argv[0] = ./myprog argv[1] = this argv[2] = is argv[3] = apple

  9. Fahrenheit to Celcius #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { double fahrenheit, celcius; fahrenheit = atof(argv[1]); celcius = (fahrenheit-32)*5.0/9; printf("Celcius = %f\n",celcius); }

  10. Arguments to main() fox01> ./fahtocelcius 36 Celcius = 2.222222

  11. Fahrenheit to Celcius #include <stdio.h> #include <stdlib.h> int main() { double fahrenheit, celcius; printf("Enter fahrenheit"); scanf("%lf",&fahrenheit); celcius = (fahrenheit-32)*5.0/9; printf("Celcius = %f\n",celcius); }

  12. Arguments to main() fox01> ./fahtocelcius2 < f.txt Enter fahrenheitCelcius = 1.111111 f.txt file has the following 34

  13. Output Redirection • Printf() sends output to stdout by default • Redirect output with > in command lime fox01> ./fahtocelcius2 > ftoc.out Enter Fahrenheit 34 fox01> ftoc.out file has the following Celcius = 1.111111

  14. Strings 14

  15. Strings • A string is an array of characters • char data[10] = “Hello”; • Use printf to print strings • printf(“%s”,data); • Can be accessed char by char • data[0] is first character End of String Symbol H e l l o \0 0 1 2 3 4 5 6 7 8 9 data 15

  16. Strings • Each character has an integer representation a b c d e … … … … z 97 98 99 100 101 ………………………112 A B C D E … … … … Z 65 66 67 68 69 ……………………… 90 0 1 2 3 4 5 6 7 8 9 48 49 50 51 52 53 54 55 56 57 \0 \n 16 0 10

  17. Strings • Characters can be interpreted as integers char c = ‘A’; printf(“%c\n”,c); prints A printf(“%d\n”,c); prints 65 printf(“%c\n”,65); prints A 17

  18. String Literals String literal values are represented by sequences of characters between double quotes (“) Examples “” - empty string “hello” “a” versus ‘a’ ‘a’ is a single character value (stored in 1 byte) as the ASCII value for a “a” is an array with two characters, the first is a, the second is the character value \0

  19. Referring to String Literals String literal is an array, can refer to a single character from the literal as a character Example: printf(“%c”,”hello”[1]); outputs the character ‘e’ During compilation, C creates space for each string literal (# of characters in the literal + 1) referring to the literal refers to that space (as if it is an array)

  20. Duplicate String Literals Each string literal in a C program is stored at a different location So even if the string literals contain the same string, they are not equal (in the == sense) Example: char string1[6] = “hello”; char string2[6] = “hello”; but string1 does not equal string2 (they are stored at different locations)

  21. String Variables Allocate an array of a size large enough to hold the string (plus 1 extra value for the delimiter) Examples (with initialization): char str1[6] = “Hello”; char str2[] = “Hello”; char *str3 = “Hello”; char str4[6] = {‘H’,’e’,’l’,’l’,’o’,’\0’}; Note, each variable is considered a constant in that the space it is connected to cannot be changed str1 = str2; /* not allowable, but we can copy the contents of str2 to str1 (more later) */

  22. Changing String Variables Can change parts of a string variable char str1[6] = “hello”; str1[0] = ‘y’; /* str1 is now “yello” */ str1[4] = ‘\0’; /* str1 is now “yell” */ Important to retain delimiter (replacing str1[5] in the original string with something other than ‘\0’ makes a string that does not end) Have to stay within limits of array

  23. String Input Use %s field specification in scanf to read string ignores leading white space reads characters until next white space encountered C stores null (\0) char after last non-white space char Reads into array (no & before name, array is a pointer) Example: char Name[11]; scanf(“%s”,Name); Problem: no limit on number of characters read (need one for delimiter), if too many characters for array, problems may occur

  24. String Input Can use the width value in the field specification to limit the number of characters read: char Name[11]; scanf(“%10s”,Name); Remember, you need one space for the \0 width should be one less than size of array Strings shorter than the field specification are read normally, but C always stops after reading 10 characters

  25. String Input (cont) Edit set input %[ListofChars] ListofChars specifies set of characters (called scan set) Characters read as long as character falls in scan set Stops when first non scan set character encountered Note, does not ignore leading white space Any character may be specified except ] Putting ^ at the start to negate the set (any character BUT list is allowed) Examples: scanf(“%[-+0123456789]”,Number); scanf(“%[^\n]”,Line); /* read until newline char */

  26. String Output Use %s field specification in printf: characters in string printed until \0 encountered char Name[10] = “Rich”; printf(“|%s|”,Name); /* outputs |Rich| */ Can use width value to print string in space: printf(“|%10s|”,Name); /* outputs | Rich| */ Use - flag to left justify: printf(“|%-10s|”,Name); /* outputs |Rich | */

  27. Input/Output Example #include <stdio.h> int main() { char LastName[11]; char FirstName[11]; printf("Enter your name (last , first): "); scanf("%10s%*[^,],%10s",LastName,FirstName); printf("Nice to meet you %s %s\n", FirstName,LastName); }

  28. Reading a Whole Line Commands: char *gets(char *str) reads the next line (up to the next newline) from keyboard and stores it in the array of chars pointed to by str returns str if string read or NULL if problem/end-of-file not limited in how many chars read (may read too many for array) newline included in string read char *fgets(char *str, int size, FILE *fp) reads next line from file connected to fp, stores string in str fp must be an input connection reads at most size characters (plus one for \0) returns str if string read or NULL if problem/end-of-file to read from keyboard: fgets(mystring,100,stdin) newline included in string read

  29. Printing a String Commands: int puts(char *str) prints the string pointed to by str to the screen prints until delimiter reached (string better have a \0) returns EOF if the puts fails outputs newline if \n encountered (for strings read with gets or fgets) int fputs(char *str, FILE *fp) prints the string pointed to by str to the file connected to fp fp must be an output connection returns EOF if the fputs fails outputs newline if \n encountered

  30. fgets/fputs Example #include <stdio.h> int main() { char fname[81]; char buffer[101]; FILE *instream; printf("Show file: "); scanf("%80s",fname); if ((instream = fopen(fname,"r")) == NULL) { printf("Unable to open file %s\n",fname); exit(-1); }

  31. fgets/fputs Example (cont) printf("\n%s:\n",fname); while (fgets(buffer,sizeof(buffer)-1,instream)!= NULL) fputs(buffer,stdout); fclose(instream); }

  32. Printing to a String The sprintf function allows us to print to a string argument using printf formatting rules First argument of sprintf is string to print to, remaining arguments are as in printf Example: char buffer[100]; sprintf(buffer,”%s, %s”,LastName,FirstName); if (strlen(buffer) > 15) printf(“Long name %s %s\n”,FirstName,LastName);

  33. sprintf Example #include <stdio.h> #include <string.h> void main() { FILE *instream; FILE *outstream; char basefname[81]; char readfname[101]; char savefname[81]; char buffer[101]; int fnum; printf("File Prefix: "); scanf("%80s",basefname); printf("Save to File: "); scanf("%80s",savefname); if ((outstream = fopen(savefname,"w")) == NULL) { printf("Unable to open %s\n", savefname); exit(-1); }

  34. sprintf Example for (fnum = 0; fnum < 5; fnum++) { /* file name with basefname as prefix, fnum as suffix */ sprintf(readfname,"%s.%d",basefname,fnum); if ((instream = fopen(readfname,"r")) == NULL) { printf("Unable to open input file %s\n",readfname); exit(-1); } while (fgets(buffer,sizeof(buffer)-1,instream) != NULL) fputs(buffer,outstream); fclose(instream); } fclose(outstream); }

  35. Reading from a String The sscanf function allows us to read from a string argument using scanf rules First argument of sscanf is string to read from, remaining arguments are as in scanf Example: char buffer[100] = “A10 50.0”; sscanf(buffer,”%c%d%f”,&ch,&inum,&fnum); /* puts ‘A’ in ch, 10 in inum and 50.0 in fnum */

  36. Character Functions toupper(ch) If ch is a lowercase letter, this function returns the corresponding uppercase letter; otherwise, it returns ch isdigit(ch) Returns a nonzero value if ch is a decimal digit; otherwise, it returns a zero. islower(ch) Returns a nonzero value if ch is a lowercase letter; otherwise, it returns a zero. isupper(ch) Returns a nonzero value if ch is an uppercase letter; otherwise, it returns a zero. isalpha(ch) Returns a nonzero value if ch is an uppercase letter or a lowercase letter; otherwise, it returns a zero. isalnum(ch) Returns a nonzero value if ch is an alphabetic character or a numeric digit; otherwise, it returns a zero. isspace(ch) Returns a non-zero value if ch is a white-space character (‘ ‘,’\t’, ‘\n’…)

  37. Data Files

  38. Data Files • Read input of a program from a file • Write output of a program to a file • Files are stored on disk • Consider the following example Output Input 3 3 3 1 3 3 3 1 3 3 3 1 1 2 3 Equilateral Isosceles Isosceles Isosceles Scalene

  39. Data Files Each data file must have a filepointer • file pointer must be defined • FILE *sensor1; • FILE *balloon; • file pointer must be associated with a specific file using the fopen function • sensor1 = fopen(“sensor1.dat”, “r”); • balloon = fopen(“balloon.dat”, “w”); Read information from file Write information to a file

  40. I/O Statements • Input file - use fscanf instead of scanf • fscanf(sensor1, “%1f %lf”, &t, &motion); • Output file - use fprint instead of printf • fprintf(balloon, “%f %f %f\n”, time, height, velocity);

  41. End of file controlled loop #include <stdio.h> int main() { FILE *scorefile; int score; scorefile = fopen("scores.txt","r"); while (feof(scorefile) <= 0) { fscanf(scorefile,"%d",&score); printf("%d\n",score); } fclose(scorefile); return(0); } Available on webpage as lecture2e11.c File 56 78 93 24 85 63 Available on webpage as scores.txt

  42. Exercise • Given a file of integers. Write a program that finds the minimum number in a file. • // algorithm to find minimum in a file open file set minimum to a large value while (there are items to read) read next number x from file if (x < min) min = x display the minimum close file File 56 78 93 24 85 63 Solution available on webpage as lectrue2e13.c

  43. Exercise • Given a file of integers. Write a program that searches for whether a number appears in the file or not. • // algorithm to check for y in a file open file set found to false while (there are items to read and found is false) read next number x from file if (x equals y) set found to true Display found message to user Display not found message to user close file File 56 78 93 24 85 63 Solution available on webpage as lecture2e14.c

  44. Exercise • Read from one file and write to another FILE *scorefile; FILE *outfile; int score; scorefile = fopen("scores.txt","r"); outfile = fopen("newscores.txt","w"); while (feof(scorefile) <= 0) { fscanf(scorefile,"%d",&score); fprintf(outfile,"%d\n",score); } Solution available on webpage as lecture2e15.c

  45. Exercise • Write a program that reads a number n from user and prints all the numbers 1 to n to file “numbers.txt”. 1 2 3 4 5 6 7 1 2 3 4 5 n= 5 n= 7

  46. More on inputs • Function to read a string char* fgets(strVar, maxLength, file) • Read from specified file (stdin, by default) until either maxLengh-1 chars or until a line feed char is encounted • stringVar: input buffer, need enough space; normally char array: char strvar[100];

  47. More on inputs • Function to read from a string intsscanf(inputbuffer, formatstring,…) • Same as scanf, except to get input data from inputbuffer • Normally, use fgets to read one line into an inputbuffer from a file and use sscanf to read the data.

  48. Example • sscanf(szinputbuffer,formatS,szV1,&iV2,&dV3) SeqszInputBuffer Format Cnt szV1 iV2 dV3 1 123456 123 45.67 %s %d %lf 3 '123456' 123 45.67 2 123456 123 45.67 %5s %d %lf 3 '12345' 6 123.00 3 123456 123 45.67 %[1-9] %d %lf 3 '123456' 123 45.67 4 123456 123 45.67 %[1-9],%d,%10lf 1 '123456' n/a n/a 5 123456,123,45.67 %[1-9],%d,%10lf 3 '123456' 123 45.67 6 123456,123,45.67 %[^,],%d,%10lf 3 '123456' 123 45.67 7 123456,123,45.67 %6[^,] ,%d,%10lf 3 '123456' 123 45.67 8 123456 , 123,45.67 %[^,],%d,%10lf 3 '123456 ' 123 45.67 9 123456 , 123,45.67 %[^, ],%d,%10lf 1 '123456' n/a n/a 10 123456 , 123,45.67 %[^, ] ,%d,%10lf 3 '123456' 123 45.67 11 123456 , 123,45.67 %[^, ] ,%d,%10lf 3 '123456' 123 45.67 12 123456 , 123,45.67 %[^, ] ,%d,%10lf 3 '123456' 123 45.67 13 123456,123,45.67 %[^,] %d %10lf 1 '123456' n/a n/a

  49. Errors to stderr • Errors should be output to stderr using fprintf rather to stdout using printf( ) • Do this • fprintf( stderr, “this is the error message\n” ); instead of this • printf( “this is the error message\n” ); • For example ofp = fopen("test.out", “w") ; if (ofp == NULL) { fprintf (stderr, "Error opening test.out\n"); exit (-1); }

  50. Header Files • Split program into multiple files • File is included during compilation • Only the c file is compiled

More Related