Input and Output in C.

Slides:



Advertisements
Similar presentations
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Advertisements

1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Strings A string is a sequence of characters treated as a group We have already used some string literals: –“filename” –“output string” Strings are important.
Expressions, Data Conversion, and Input
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
Chapter 9 Formatted Input/Output Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
File IO and command line input CSE 2451 Rong Shi.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
Files A collection of related data treated as a unit. Two types Text
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
1 Midterm 1 Review. 2 Midterm 1 on Friday February 27 Closed book, closed notes No computer can be used 50 minutes 4 or 5 questions write full programs.
1 C Syntax and Semantics Dr. Sherif Mohamed Tawfik Lecture Two.
SCP1103 Basic C Programming SEM1 2010/2011 Arithmetic Expressions Week 5.
Chapter 9 - Formatted Input/Output
C Formatted Input/Output
Arithmetic Expressions
Strings CSCI 112: Programming in C.
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
TMF1414 Introduction to Programming
File Access (7.5) CSE 2031 Fall July 2018.
Multiple variables can be created in one declaration
Chapter 18 I/O in C.
File I/O.
Introduction to C CSE 2031 Fall /3/ :33 AM.
A First Book of ANSI C Fourth Edition
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
Strings A string is a sequence of characters treated as a group
Computer Science 210 Computer Organization
CS111 Computer Programming
File Input/Output.
Chapter 2 part #3 C++ Input / Output
Programming in C Input / Output.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Computer Science 210 Computer Organization
Programming in C Input / Output.
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
Increment and Decrement
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Arithmetic Expressions & Data Conversions
Chapter 9 - Formatted Input/Output
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
File Input and Output.
File Handling.
Strings.
Programming in C Input / Output.
Chapter 2 part #3 C++ Input / Output
Module 12 Input and Output
Introduction to C EECS May 2019.
Strings 1.
Variables in C Topics Naming Variables Declaring Variables
CS1100 Computational Engineering
Introduction to C Programming
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Professor Jodi Neely-Ritz University of Florida
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

Input and Output in C

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>

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

Conversion Specifiers for Output Statements Frequently Used

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

Conversion Specifiers for Input Statements Frequently Used

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; }

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

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); }

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

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); }

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

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

Strings 14

Strings A string is an array of characters Use printf to print strings 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

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 1 2 3 4 5 6 7 8 9 48 49 50 51 52 53 54 55 56 57 \0 \n 10 16

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

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

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)

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)

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) */

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

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

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

String Input (cont) Edit set input %[ListofChars] Examples: 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 */

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 | */

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); }

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) to read from keyboard: fgets(mystring,100,stdin)

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

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); }

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

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);

sprintf Example printf("File Prefix: "); scanf("%80s",basefname); #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); }

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);

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 */

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’…)

Data Files

Data Files Output Input 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 Scalene

Read information from file Data Files Each data file must have a file pointer 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

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);

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

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

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

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

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

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];

More on inputs Function to read from a string int sscanf(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.

Example sscanf(szinputbuffer,formatS,szV1,&iV2,&dV3) Seq szInputBuffer 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

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); }

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

Header Files File: lecture3header.h double x; double y; char color; double width; double height;

Header Files REST OF YOUR PROGRAM File: lecture3example.c #include <stdio.h> #include <stdlib.h> #include "lecture3header.h" REST OF YOUR PROGRAM

Data Conversion Sometimes it is convenient to convert data from one type to another For example, in a particular situation we may want to treat an integer as a floating point value These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation

Data Conversion Conversions must be handled carefully to avoid losing information Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) Data conversions can occur in three ways: assignment conversion promotion casting

Assignment Conversion Assignment conversion occurs when a value of one type is assigned to a variable of another For example, the following assignment converts the value stored in the dollars variable to a double value double money; int dollars = 123; money = dollars; // money == 123.0 Only widening conversions can happen via assignment The type and value of dollars will not be changed

double result = sum / count; Data Conversion Promotion happens automatically when operators in expressions convert their operands For example, if sum is a double and count is an int, the value of count is promoted to a floating point value to perform the following calculation: double result = sum / count; The value and type of count will not be changed

double result = (double) total / count; Casting Casting is a powerful and dangerous conversion technique Both widening and narrowing conversions can be done by explicitly casting a value To cast, the desired type is put in parentheses in front of the value being converted For example, if total and count are integers, but we want a floating point result when dividing them, we cast total or count to a double for purposes of the calculation: double result = (double) total / count; Then, the other variable will be promoted, but the value and type of total and count will not be changed