CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
Strings Input/Output scanf and printf sscanf and sprintf gets and puts.
Strings.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 09 Strings, IDEs. METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan Mon July 29, 2002.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Strings CS240 Dick Steflik. What is a string A null terminated array of characters: char thisIsAString[10]; \0 The “\0” (null character)
ECE Application Programming Instructor: Dr. Michael Geiger Spring 2012 Lecture 31: PE5.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Chapter 10.
N-1 University of Washington Computer Programming I Lecture 19: Strings © 2000 UW CSE.
Introduction to Computers and Programming Class 22 Character Arrays (Strings) Professor Avi Rosenfeld.
Strings A special kind of array is an array of characters ending in the null character \0 called string arrays A string is declared as an array of characters.
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.
Introduction to C programming
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
CS 108 Computing Fundamentals March 26, Class Notes Last day to withdraw from a class is Monday, April 6 Next week I sent s to a small number.
BBS514 Structured Programming (Yapısal Programlama)1 Character Processing, Strings and Pointers,
STRING Dong-Chul Kim BioMeCIS UTA 10/7/
CSC 270 – Survey of Programming Languages C Lecture 4 – Strings Heavily borrowed from Dr. Robert Siegfried and Dietel How to Program in C Powerpoint Presentations.
CPT: Strings/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to discuss strings and their relationship.
CS 162 Introduction to Computer Science Chapter 17 C++ String Objects Herbert G. Mayer, PSU (Copied from Prof. Phillip Wong at PSU) Status 11/30/2014.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
File IO and command line input CSE 2451 Rong Shi.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
CSC 270 – Survey of Programming Languages
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
String Array (Multidimensional Arrays) 1. A string array is a multidimensional array of strings. It is declared in the following syntax: char variable_name[No_of_strings][size_of_each_string];
Strings, Pointers and Tools
CMSC 104, Version 8/061L25Strings.ppt Strings Topics String Libraries String Operations Sample Program Reading Sections
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
Today’s Material Strings Definition Representation Initialization
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
Dr. Sajib Datta Feb 21,  In the last class we discussed: ◦ Bubble sort  How it works  performance.
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.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Strings CSCI 112: Programming in C.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
INC 161 , CPE 100 Computer Programming
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
ECE Application Programming
Characters and Strings
Lecture 8 String 1. Concept of strings String and pointers
CSE 303 Lecture 14 Strings in C
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
Arrays in C.
Computer Science 210 Computer Organization
Strings.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Chapter 8 Character Arrays and Strings
Strings Adapted from Dr. Mary Eberlein, UT Austin.
CS31 Discussion 1H Fall18: week 6
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Presentation transcript:

CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O

CSE 251 Dr. Charles B. Owen Programming in C2 Character Type: char In C, characters are indicated by single quotes: char myChar; myChar = 'a'; printf(“myChar is %c\n”, myChar); The type is char for one (1) character %c is the formal specifier for a char

CSE 251 Dr. Charles B. Owen Programming in C3 String A string is an array of characters, it is indicated by double quotes: "this is a string" But you can’t use an assignment operator to assign a string to a character array char myChar[80];/* array of chars */ myChar[4] = ‘a’;/* OK */ myChar = “this is a string”;/* NOT OK */

CSE 251 Dr. Charles B. Owen Programming in C4 String A null (‘\0’) character is placed to mark the end of each string String functions use ‘\0’ to locate end of string (so you don’t have to pass string length as argument to the functions) tsisihas\0gnirt

CSE 251 Dr. Charles B. Owen Programming in C5 Initializing a String char myStr[5] = {‘a’, ’b’, ’c’, ’d’, 0}; printf(“myStr is %s\n”, myStr); – Array size has exactly 5 elements – A terminating ‘\0’ character at the end (in ASCII, char ‘\0’ is equivalent to int 0) – Will print: “myStr is abcd” myStr \0dcba

CSE 251 Dr. Charles B. Owen Programming in C6 Another way char myStr[10]=“birdbath”; printf(“myStr is %s\n”, myStr); – Ok to use assignment only to initialize string – myStr is an array of 10 characters (but only the first 8 elements used to store the word) – a ‘\0’ is added to the end automatically (so 9 elements in the array are occupied) myStr bir\0htabd

CSE 251 Dr. Charles B. Owen Programming in C7 Better way char myStr[]=“birdbath”; printf(“myStr is %s\n”, myStr); – ‘\0’ is added automatically to the end of myStr – Space is allocated automatically to hold exactly what we need (9 locations, including ‘\0’) bir\0htabd myStr

CSE 251 Dr. Charles B. Owen Programming in C8 printf for Strings char myStr[] = “abc123”; Output: – Use %s to print the entire string: printf(“%s\n”,myStr); /* outputs abc123 */ /* ‘\0’ is not printed */ – Use %c to print a character: printf(“%c\n”,myStr[1]); /* outputs: b */

CSE 251 Dr. Charles B. Owen Programming in C9 String input There are several functions available Part of the stdio.h library.

CSE 251 Dr. Charles B. Owen Programming in C10 scanf scanf reads up to the first white space, ignores the stuff typed in after that. Be careful when using it. char myStr[10]; printf(“Enter a string: “); scanf(“%s”, myStr); printf(“You entered %s\n\n”, myStr)

CSE 251 Dr. Charles B. Owen Programming in C11 scanf - safer Use %[width]s to copy only up to a maximum number of character. But, does not append the ‘\0’ char myStr[10]; printf(“Enter a string: “); scanf(“%9s”, myStr); myStr[9] = ‘\0’;/* Do this yourself just in case */ printf(“You entered %s\n\n”, myStr)

CSE 251 Dr. Charles B. Owen Programming in C12 getchar getchar will fetch one (1) character from the input stream char myChar; printf(“Enter a character: “); myChar = getchar(); printf(“You entered %c\n\n”, myChar);

CSE 251 Dr. Charles B. Owen Programming in C13 fgets char * fgets(charArray, lengthLimit, filePtr) fetches a whole line, up to the size limit or when it sees a new line It will add a ‘\0’ at the end of string Example: char myStr[80]; fgets(myStr, 80, stdin); // fetch from console Returns a NULL if something went wrong, otherwise a pointer to the array The functions that start with “f” work with any source of input. stdin is the C “Standard Input”.

CSE 251 Dr. Charles B. Owen Programming in C14 #include int main () { int inputLength=20 int cnt=0; char str1[20], str2[20]; printf("\nEnter a string: "); fgets(str1, inputLength, stdin); printf("You entered %s\n",str1); printf(“Enter another string: "); scanf("%s",str2); printf("You entered %s\n",str2); } Make sure you’re clear the difference between fgets and scanf

CSE 251 Dr. Charles B. Owen Programming in C15 Note the extra new line when using fgets tsisihas\ngnirt\0 str1 (read using fgets) str2 (read using scanf) t\0sih 1

CSE 251 Dr. Charles B. Owen Programming in C16 String manipulation functions strcpy – Copies a string strcat – Concatenates two strings strlen – Returns the length of a string strcmp – Compares two strings #include

CSE 251 Dr. Charles B. Owen Programming in C17 string copy (strcpy) char [] strcpy (char dest[], const char src[]); copy string contents from src (2 nd arg) to dest (1 st arg) including ‘\0’ dest is changed, src unmodified (but can do some weird things) returns a pointer to the modified dest array strcpy(destString, srcString);

CSE 251 Dr. Charles B. Owen Programming in C18 string copy (strcpy) char [] strcpy (char dest[], const char src[]); There is no error checking! – If dest array is shorter than src array, no errors. Weird things could happen, but no compile errors and often no runtime errors – Tracking these “bugs” down is very hard!

CSE 251 Dr. Charles B. Owen Programming in C19 Safer version of string copy char [] strncpy (char dest[], const char src[], int N); copies at most N characters from src to dest (or up to ‘\0’ If length of src is greater than N, copies only the first N characters If length of src is less than N, pad the remaining elements in dest with ‘\0’ strncpy(destString, srcString, 80); Does not copy the ‘\0’ if the string length is >= N

CSE 251 Dr. Charles B. Owen Programming in C20 concatenation (strcat) char [] strcat(char dest[], const char src[]) contents of src are added to the end of dest. dest is changed, src is not ‘\0’ added to the end of dest return a pointer to dest no bounds check (again, this is C)

CSE 251 Dr. Charles B. Owen Programming in C21 comparison (strcmp) int strcmp (const char s1[], const char s2[]); Compares 2 strings – if s1 precedes s2, return value is less than 0 – if s2 precedes s1, return value is greater than 0 – if s1 equal to s2, return value is 0 Comparison is based on lexicographic order (ASCII order) – e.g., “a” < “b”

CSE 251 Dr. Charles B. Owen Programming in C22 #include int main() { printf("strcmp(\"a\",\"b\"): %d\n", strcmp("a","b")); printf("strcmp(\"b\",\"a\"): %d\n", strcmp("b","a")); printf(“strcmp(\"a\",\"a\"): %d\n", strcmp("a","a")); printf("strcmp(\"2\",\"3\"): %d\n", strcmp("2","3")); printf("strcmp(\"2\",\"10\"): %d\n", strcmp("2","10")); } Lexicographic ordering is not the same as ordering numbers

CSE 251 Dr. Charles B. Owen Programming in C23 Reversing a string Input: Math is fun Output: nuf si htaM How would you do this?

CSE 251 Dr. Charles B. Owen Programming in C24 front back void Reverse(char str[] ) { int front = 0; int back = strlen(str) - 1; char t; /* A temporary place to put a character */ while (front < back) { t = str[front]; str[front] = str[back]; str[back] = t; front++; back--; } 2

CSE 251 Dr. Charles B. Owen Programming in C25 Built-in functions for characters These all return boolean (1/0). – isalnum(c): is c alphanumeric? – isalpha(c): is c alphabetic? – isdigit(c): is c a digit? – iscntrl(c): is c a control character? – islower(c): is c lower case? – isupper(c): is c upper case? – ispunct(c): is c a punctuation character, that is a printable character that is neither a space nor an alphanumeric character #include

CSE 251 Dr. Charles B. Owen Programming in C26 converters char tolower(c) – return the character as lower case char toupper(c) – return the character as upper case

CSE 251 Dr. Charles B. Owen Programming in C27 File IO How to write programs to read from or write to files So far, we’ve only looked at how to read/write to the console

CSE 251 Dr. Charles B. Owen Programming in C28 Open files Files are opened with fopen – the fopen function is part of stdio.h – It takes two args: a string (the name of a file) and a mode string (how the file is opened). – It returns a file pointer fptr = fopen(“myfile.txt”,”r”);

CSE 251 Dr. Charles B. Owen Programming in C29 Declare and assign file pointer fopen returns a NULL pointer if it cannot perform the operation FILE *infile; inFile = fopen(“file.txt”,”r”); if (inFile == NULL) // bad file opening

CSE 251 Dr. Charles B. Owen Programming in C30 file modes “r”, read from the beginning of an existing file “w”, make an empty file (wipe out old contents), start writing. “a”, find an existing file, start writing at the end of that file

CSE 251 Dr. Charles B. Owen Programming in C31 Close files Files are closed with fclose – the fclose function is part of stdio.h – It takes one argument: pointer to the file to be closed fclose(fptr);

CSE 251 Dr. Charles B. Owen Programming in C32 The “f” functions most of the I/O functions we know have an equivalent “f” version to work with a file. The first argument is the file pointer value of an opened file – fprintf(filePtr, “format string”, values) – fscanf(filePtr, “format string, addresses) – feof(filePtr) end of file test 3