C Programming. Unit 9. Manipulating Strings File Processing.

Similar documents
Strings. Chuan-Ming Liu. Computer Science & Information Engineering National Taipei University of Technology Taiwan

8. Characters, Strings and Files

C mini reference. 5 Binary numbers 12

Chapter 8 - Characters and Strings

Chapter 8 C Characters and Strings

C PROGRAMMING. Characters and Strings File Processing Exercise

Arrays, Strings, & Pointers

C: How to Program. Week /May/28

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Computer Science & Engineering 150A Problem Solving Using Computers

Characters and Strings

Chapter 8: Character & String. In this chapter, you ll learn about;

Standard C Library Functions

C Libraries. Bart Childs Complementary to the text(s)

Standard File Pointers

C Characters and Strings

Introduction to Computer Programming Lecture 18 Binary Files

ONE DIMENSIONAL ARRAYS

Fundamentals of Programming. Lecture 11: C Characters and Strings

File I/O. Last updated 10/30/18

UNIT IV-2. The I/O library functions can be classified into two broad categories:

10/6/2015. C Input/Output. stdin, stdout, stderr. C Language II. CMSC 313 Sections 01, 02. C opens three input/output devices automatically:

Structured programming

C programming basics T3-1 -

Introduction to string

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

Strings and Library Functions

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Fundamentals of Programming

today cs3157-fall2002-sklar-lect05 1

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

Fundamental of Programming (C)

SWEN-250 Personal SE. Introduction to C

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 11, FALL 2012

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Scientific Programming in C V. Strings

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

Appendix A Developing a C Program on the UNIX system

Input/Output: Advanced Concepts

Contents. Preface. Introduction. Introduction to C Programming

UNIT-I Input/ Output functions and other library functions

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Contents. A Review of C language. Visual C Visual C++ 6.0

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

ET156 Introduction to C Programming

Course organization. Course introduction ( Week 1)

Chapter 12. Files (reference: Deitel s chap 11) chap8

C Basics And Concepts Input And Output

File IO and command line input CSE 2451

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Computer Programming Unit v

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Input / Output Functions

CSCI 171 Chapter Outlines

ARRAYS(II Unit Part II)

Euclid s algorithm, 133

Section 3: Library Functions

by Pearson Education, Inc. All Rights Reserved.

Multiple Choice Questions ( 1 mark)

Input/Output and the Operating Systems

Approximately a Test II CPSC 206

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Chapter 9 Strings. With this array declaration: char s[10];

Unit 4. Input/Output Functions

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

PROGRAMMAZIONE I A.A. 2017/2018

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Computer Language. It is a systematical code for communication between System and user. This is in two categories.

Index. backslash character, 19 backup, off-site, 11. abs, 72 abstraction, 63, 83, 133, 141, 174, 181 acos, 72

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

C-LANGUAGE CURRICULAM

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Computers Programming Course 11. Iulian Năstac

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output

CSI 402 Lecture 2 Working with Files (Text and Binary)

Pointers and File Handling

Library Functions. General Questions

Advanced C Programming Topics

CSC 270 Survey of Programming Languages. C-String Values

DATA STRUCTURES USING C

Applied C and C++ Programming

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

Intermediate Programming, Spring 2017*

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

CS240: Programming in C

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

Transcription:

Introduction to C Programming Unit 9 Manipulating Strings File Processing skong@itt-tech.edu

Unit 8 Review Unit 9: Review of Past Material

Unit 8 Review Arrays Collection of adjacent memory cells Each element has the same data type Array declaration must include size in brackets, after name Array size is a positive integer To access array element, follow the name with subscript Subscript is an integer expression (index) in square brackets Array initializer list in braces Parallel arrays are 2 or more related arrays with identical size Can be passed as argument to function, but not returned

Strings String is not a recognized separate data type in C String variable is an array of characters Sized to accept the maximum number of characters Characters start with element zero All strings must end with a zero-value character '\0'

String Library Functions Unit 9: String Manipulation and File Processing

String Library Since strings are arrays, not single variables, can't use operators Instead, the string library provides functions strcpy(src, dest) - copy "src" (source) to "dest" (destination) strlen(s) ()-returns the length of string "" "s" (without ih 0 terminator) strcat(src, dest) - concatenate "src" to end of "dest" strcmp(s1, s2) - compares "s1" to "s2", returns an int code If s1 precedes s2, returns negative value If s2 precedes s1, returns positive value If equal, returns zero sprintf() - puts formatted data in a string sscanf() - gets formatted data from a string

Declaring and Initializing Strings Declare a string as an array of characters char string_var[30]; Declare and initialize a string char str[20] = "Initial value"

String Input & Output Input scanf("%s", &stringname); Or scanf("%s", " stringname); Output Output printf("%s\n", stringname);

Figure 9.1 Right and Left Justification of Strings

Formatting String Output Right-justified strings printf("***%8s***%3s***\n", "Short", "Strings"); *** Short***Strings*** Strings Left-justified strings printf("%-20s\n", president);

Figure 9.3 Execution of scanf ("%s", dept);

#define NUM_LENGTH 10 #include <stdio.h> int main(void){ char inp_numstr[num_length]; int inp_num; printf("enter integer only up 10 digit in length \n"); scanf("%s", inp_numstr); printf("input number is : %s\n", inp_numstr); inp_num = atoi(inp_numstr); /* convert string to int*/ printf("converted number is %d\n", inp_num); }

Input and Output for an Array of Strings #define NUM_PEOPLE 30 #define NAME_ LEN 25... char names[num_people][name_len]; for (i = 0; i < NUM_PEOPLE; ++i) { scanf( %s%d, names[i]); printf( %-35s\n,names[i]); }

Functions in string.h Copy one string to another strcpy strncpy Concatenate strings strcat strncat Compare strings strcmp strncmp Learn string length strlen Separate a string using a delimiter strtok

String Assignment Cannot use standard assignment except during initialization char one_str[20]; one_str = "Test string" /*illegal*/ Use strcpy or strncpy instead char one_str[20]; strcpy(one_str, "Test String"); strncpy(one _ str, "Test String", 20);

Copying Substrings Use strncpy to identify the number of characters to copy. char month[5]; char s1[15] = "Jan. 30, 1996"; strncpy(month, s1, 4); month[4] = '\0';

Copying a Substring from the Middle Pass a pointer to the element where the copy should start. char day[3]; char s1[15] = "Jan. 30, 1996"; strncpy(day, &s1[5], 2); Day[2] = '\0';

Concatenating Strings - strcat Use strcat to concatenate one entire string onto another. #define STRSIZ 10 char first[strsiz] = Georg ; char last[strsiz] = Ohm"; strcat(first, st, last); // GeorgOhm"

Concatenating Strings - strncat Avoid overflow. #define STRSIZ 12 char first[strsiz] = "Alessandro ; char last[strsiz] = Volta"; AlessandroVolta is > than 12! strncat(first, last, 1); /* AlessandroV"*/

Comparison char str1[]= Amp, str2[]= Volt ; if (str1==str2) // this does not work!!! if (strcmp(str1,str2)==0) //does work!!!

Finding the String's Length Use strlen to determine the number of characters in a string - \0 not counted. char s1[] = "Charles Coulomb"; for (i=0; i<strlen(s1) ;i++) if (strcmp(s1[i], )==0 printf( Found space\n ); strtok is a special function that will return portions of a string based upon a token. i.e. a comma or dash or space

Character vs. String

Character Input & Output ctype.h Library Get a single character from standard input: int ch; ch = getchar(); Output a character to standard out: putchar(ch);

Figure 9.15 Implementation of scanline Function Using getchar

Character Analysis and Conversion isalpha is character A-Z or a-z isdigit is character 0-9 islower is character lower case isupper is character upper case ispunct is character punctuation mark isspace is character a whitespace character (space, tab, newline) tolower Convert to lower case toupper Convert to upper case ** Note ctype.h library needed for all the functions

Using Files in C Unit 9: String Manipulation and File Processing

Files in C All file functions require a file pointer (FILE *) The file library functions (in <stdio.h>) perform file ops Must open a file before using it fopen() library function - returns a file pointer Can open for binary or text file access Text files store data in readable characters - easy to change with editor Binary files store data in machine format - faster to read and write Can open for reading or writing Reading - accesses but does not change a file, used for input Writing - empties or creates a file, then program outputs data When finished using a file, close it with fclose()

Working With Text Files Text files treated like sequential stream of bytes Typically processed from beginning to end To output data to a text file fprintf() - Like printf(), but output goes to the file putchar() - Can output one character at a time to the file puts() - Can output a string to the file To input data from a text file fscanf() -Like scanf(), but input comes from the file getchar() - Can input one character at a time from the file gets() - Can input a string from the file

Working With Binary Files File is a sequential collection of binary data bytes Typically processed from beginning to end Function fwrite() used to output binary data Must provide address of variable, number of bytes, a multiplier (useful for an array size), and file pointer Function fread() used to input binary data Must provide address of variable, number of bytes, a multiplier (useful for an array size), and file pointer

Newline and EOF Newline Represented by '\n' Added from the keyboard by using a carriage return EOF Represents the end of a file Example This is a text file!<newline> It has two lines.<newline><eof>

EOF Example for (status = scanf("%d", &num); status!= EOF; status = scanf("%d", &num)) processnum();

EOF Sample Code -1 Figure 5.11 Batch Version of Sum of Exam Scores Program /* * Compute the sum of the list of exam scores stored in the file scores.dat */ #include <stdio.h> /* defines fopen, fclose, fscanf, fprintf, and EOF */ Int main(void) { FILE *inp; /* input file pointer */ int sum = 0, /* sum of scores input so far */ score, /* current score */ input_status; /* status value returned by fscanf */ inp = fopen("scores.dat", "r");

EOF Sample Code -2 (continued) printf("scores\n"); input_status = fscanf(inp, "%d", &score); while (input_status!= EOF) { printf("%5d\n", score); sum += score; input_status = fscanf(inp, "%d", &score); } printf("\nsum of exam scores is %d\n", sum); fclose(inp); return (0); }

Streams Input stream Can receive from text input device or file stdin normally represents input from the keyboard Output stream Sends text to the display, a printer, or a file stdout normally represents output to the display Error stream Referenced as stderr Sends error information in a text stream Output on the display in an interactive program

Table 12.1 Escape Sequences

Escape Sequence Example Output: Final Report Using the code: printf( \f\t\t\tfinal Report\r\t\t\t \n );

Placeholders for printf Format Strings Table 12.2

Field Width, Justification, and Precision

Standard I/O vs. File Pointer I/O Table 12.4

Binary Files Advantages More optimal for storing structured data Smaller file size Read and write directly, not conversion to text stream Disadvantages Cannot create files with a text editor Cannot view files with a text editor File format proprietary to application

Binary File Functions fopen Use "wb" or "rb" as last parameter fwrite fwrite(&i, sizeof(int), 1, binaryp); fwrite(score, sizeof(int), 10, binaryp); fread fread(&i, sizeof(int), 1, binaryp); fread(score, sizeof(int), 10, binaryp); Returns number of elements successfully read

Figure 12.3 Creating a Binary File of Integers

Text Files vs. Binary Files Example #define STRSIZ 10 #define MAX 40 typedef struct { char name[strsiz]; double diameter; int moons; double orbit_time, rotation_time; } planet_t; double nums[max], data; planet_t a_planet; int I, n, status; FILE *plan_bin_inp, *plan_bin_outp, *plan_txt_inp, *plan_txt_outp; FILE *doub_bin_inp, *doub_bin_outp, *doub_txt_inp, *doub_txt_outp

Opening the Files Text plan_txt_inp = fopen("planets.tx t", "r"); doub_txt_inp = fopen("nums.txt", nums.txt "r"); plan_txt_outp = fopen("pl pl_out.txt txt ", "w"); doub_txt_inp = fopen("nm_out.txt ", "w"); Binary plan_bin_inp = fopen("planets.bi n", "rb"); doub_bin_inp = fopen("nums.bin", nums.bin "rb"); plan_bin_outp = fopen("pl pl_out.bin ", "wb"); doub_bin_inp = fopen("nm_out.bin ", "wb");

Copy One Planet Structure to Memory Text fscanf(plan_txt_inp, f( "%s%lf%d%lf%lf",%lf%d%lf%lf" a_planet.name, &a_planet.diameter, &a_planet.moons, &a_planet.orbit_time, &a_planet.rotation_time i Binary fread(&a_planet, sizeof (planet_t), t), 1, plan_bin_inp);

Write One Planet Structure to the Output File Text fprintf(plan_txt_outp, "%s %e %d %e %e", a_planet.name, a_planet.diameter, a_planet.moons, a_planet.orbit_time, time, a_planet.rotation_time Binary fwrite(&a_planet, sizeof (planet_t), 1, plan_bin_outp);

Copy an Array of Numbers to Memory Text for (i=0; i<max; ++i) { fscanf(doub_txt_inp, "%lf", &nums[i]; } Binary fread(nums, sizeof (double), MAX, doub_bin_inp);

Write an Array of Numbers to Memory Text for (i=0; i<max; ++i) { fprintf(doub_txt_outp, "%e\n", nums[i]; } Binary fwrite(nums, sizeof (double), MAX, doub_bin_outp);

Fill nums with data until EOF is reached Text for (status=fscanf(doub_txt_inp, "%lf", &data); status!= EOF && n < MAX; status=fscanf(doub_txt_inp, "%lf", &data)) nums[n++] = data; Binary n = fread(nums, sizeof (double), MAX, doub_bin_outp);