Strings and Stream I/O

Similar documents
Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

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

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

CSCE 110 PROGRAMMING FUNDAMENTALS

today cs3157-fall2002-sklar-lect05 1

System Design and Programming II

EECS402 Lecture 08. Intro To The Standard string Class. Some string Functionality

CS 103 Unit 14 - Streams

Note 11/13/2014. They are like those i s, j s, and temp s that appear and disappear when the function starts and finishes...

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Scientific Programming in C V. Strings

Lecture 5 Files and Streams

G52CPP C++ Programming Lecture 17

What we will learn about this week:

CMPS 221 Sample Final

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

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

Chapter 2. Procedural Programming

The string Class. Lecture 21 Sections 2.9, 3.9, Robb T. Koether. Wed, Oct 17, Hampden-Sydney College

CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

CS2141 Software Development using C/C++ C++ Basics

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

Array Initialization

CS103L SPRING 2018 UNIT 7: FILE I/O

Chapter 10 Characters, Strings, and the string class

CSCE 206: Structured Programming in C++

Linked List using a Sentinel

CS 0449 Sample Midterm

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Introduction. Lecture 5 Files and Streams FILE * FILE *

Chapter 8 - Characters and Strings

Streams. Rupesh Nasre.

Given the C++ declaration statement below, which of the following represents the value of exforsys? e) None of the above. 1K

Chapter 8 C Characters and Strings

C: How to Program. Week /May/28

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

File I/O Christian Schumacher, Info1 D-MAVT 2013

Chapter 10: Characters, C- Strings, and More About the string Class

Chapter 10: Character Testing. From Program Character Case Conversion 8/23/2014. Character Testing. Character Case Conversion

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes:

CS 103 Unit 14 - Streams

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Due Date: See Blackboard

String Class in C++ When the above code is compiled and executed, it produces result something as follows: cin and strings

CS2255 HOMEWORK #1 Fall 2012

Chapte t r r 9

Characters and Strings

4 Strings and Streams. Testing.

Chapter 15 - C++ As A "Better C"

Scientific Computing

Fundamentals of Programming. Lecture 11: C Characters and Strings

CS31 Discussion. Jie(Jay) Wang Week6 Nov.4

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

10/23/02 21:20:33 IO_Examples

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

8. Characters, Strings and Files

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 10: Characters, C- Strings, and More About the string Class Character Testing

CSE 100: STREAM I/O, BITWISE OPERATIONS, BIT STREAM I/O

Chapter 14 Sequential Access Files

Structured programming

primitive arrays v. vectors (1)

Exercise 1.1 Hello world

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Streams in C++ Stream concept. Reference information. Stream type declarations

Engineering Problem Solving with C++, Etter

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

C++_ MARKS 40 MIN

The University of Nottingham

CS201- Introduction to Programming Current Quizzes

Dodatak D Standardna string klasa

A SHORT COURSE ON C++

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

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

C mini reference. 5 Binary numbers 12

COMP322 - Introduction to C++

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

W3101: Programming Languages C++ Ramana Isukapalli

C++ Input/Output: Streams

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

I/O Streams and Standard I/O Devices (cont d.)

CSE 100: STREAM I/O, BITWISE OPERATIONS, BIT STREAM I/O

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

struct Buffer { Buffer(int s) { buf = new char[s]; } ~Buffer() { delete [] buf; } char *buf; };

CPSC 427: Object-Oriented Programming

C++ files and streams. Lec 28-31

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

CS 247: Software Engineering Principles. ADT Design

CS302 - Data Structures using C++

Introduction to C++ (Extensions to C)

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

Transcription:

Strings and Stream I/O

C Strings In addition to the string class, C++ also supports old-style C strings In C, strings are stored as null-terminated character arrays str1 char * str1 = "What is your name? "; char str2[] = "How old are you? "; char arr1[] = {'H','o','w',' ','o','l','d',' ', 'a','r','e',' ','y','o','u','?',' '; W h a t i s y o u r n a m e? \0 str2 H o w o l d a r e y o u? \0 arr1 H o w o l d a r e y o u?

C Library String Functions #include <string.h> #include <stdlib.h> void F() { char message[100]; // copy string into message strcpy(message, "The following error has occurred:"); // concatenate string to message strcat(message, "Out of memory"); // compute length of the string int msglen = strlen(message); // convert a string to an integer int num = atoi("-272");

int strlen(const char *str) { int len = 0; const char * p = str; while (*p!= '\0') { ++len; ++p; return len; C String Examples void strcpy(char * dest, const char * src) { char * d = dest; const char * s = src; while (*s!= '\0') { *d++ = *s++; *d = '\0'; void strcat(char * str1, const char * str2) { strcpy(str1 + strlen(str1), str2);

#include <string.h> #include <iostream> using namespace std; Dynamic String Allocation void F() { const char * A = "Hello"; const char * B = ", "; const char * C = "how are you today?" char * message; int msglen = strlen(a) + strlen(b) + strlen(c); message = new char[msglen + 1]; strcpy(message, A); strcat(message, B); strcat(message, C); cout << message << endl; delete [] message;

Using C Strings with C++ Strings Sometimes you need to convert a C string to a C++ string, and vice versa C string to C++ string Initialize a C++ string with a C string string name("fred"); Assign a C string to a C++ string name = "fred"; C++ string to C string All C runtime library functions require C strings The string class has a method named c_str that returns a pointer to a C string int x = atoi(numstr.c_str());

C Library Character Classification Functions #include <ctype.h> isalpha isdigit isalnum isspace islower isupper isprint iscntrl many others

Command-Line Arguments Command-line arguments are passed as parameters to the main function int main(int argc, char *argv[]) You can omit these parameters if you don't need to process command-line arguments The first parameter, argc, is a count of how many command-line arguments there are The second parameter, argv, is an array of C strings that are the values of the command-line arguments argv[0] contains the name of the program executable argv[1].. argv[argc-1] contain the actual command-line arguments

Command-Line Arguments printargs.cpp #include <iostream> using namespace std; int main(int argc, char *argv[]) { for (int i=0; i < argc; ++i) { cout << argv[i] << endl; $./printargs Computer Science 240./printargs Computer Science 240 $

Stream I/O A stream is an ordered sequence of bytes Streams are a useful abstraction for doing I/O Input comes from the keyboard, files, network connections, and memory Output goes to the screen, files, network connections, and memory All of these I/O sources and destinations can be viewed as byte streams

C++ Stream I/O Library C++ has an extensive set of classes for doing stream-based I/O In class we will learn enough about stream I/O to do the programming projects The textbook provides much more information than will be covered in class If you want to put C++ on your resume, Read The Book!

Stream Class Hierarchy ios istream ostream ifstream istrstream iostream ofstream ostrstream fstream strstream

Formatted and Unformatted I/O The C++ stream classes support both formatted and unformatted I/O Formatted I/O Overloaded stream insertion << and extraction >> operators Unformatted I/O Read/write one character at a time Read/write one line at a time

#include <string> #include <fstream> #include <iostream> using namespace std; Reading Lines From a Text File bool ReadLine(istream & stream, string & line) { int main(int argc, char * argv[]) { if (argc == 2) { ifstream file(argv[1]); if (file) { string line; while (ReadLine(file, line)) { cout << line << endl; file.close(); return 0; else { cout << "Could not open file " << argv[1] << endl; else { cout << "Invalid arguments" << endl; return -1;

ReadLine (version 1) bool ReadLine(istream & stream, string & line) { const int BUF_SIZE = 1000; char buf[buf_size]; stream.getline(buf, BUF_SIZE); if (stream) { line = buf; return true; else { return false;

ReadLine (version 2) bool ReadLine(istream & is, string & line) { if (!is) { return false; line = ""; while (true) { char c; is.get(c); if (is) { if (c == '\n') { return true; else { line += c; else { return true;

#include <string> #include <fstream> #include <iostream> using namespace std; Writing to a Text File void WriteHTMLPage(ostream & stream) { int main(int argc, char * argv[]) { if (argc == 2) { ofstream file(argv[1]); if (file) { WriteHTMLPage(file); file.close(); return 0; else { cout << "Could not open file " << argv[1] << endl; else { cout << "Invalid arguments" << endl; return -1;

WriteHTMLPage void WriteHTMLPage(ostream & stream) { stream << "<HTML>" << endl; stream << " <HEAD>" << endl; stream << " <TITLE>CS 240</TITLE>" << endl; stream << " </HEAD>" << endl; stream << " <BODY>" << endl; stream << " <H1>Welcome to CS 240!</H1>" << endl; stream << " </BODY>" << endl; stream << "</HTML>" << endl;

#include <string> #include <strstream> #include <iostream> using namespace std; Writing to a String void WriteHTMLPage(ostream & stream) { stream << "<HTML>" << endl; stream << " <HEAD>" << endl; stream << " <TITLE>CS 240</TITLE>" << endl; stream << " </HEAD>" << endl; stream << " <BODY>" << endl; stream << " <H1>Welcome to CS 240!</H1>" << endl; stream << " </BODY>" << endl; stream << "</HTML>" << endl; int main() { ostrstream stream; WriteHTMLPage(stream); stream << ends; // writes '\0' to the stream cout << stream.str(); return 0;

#include <string> #include <strstream> #include <iostream> using namespace std; Reading Words From a String int main(int argc, char * argv[]) { if (argc == 2) { istrstream stream(argv[1]); int count = 0; while (true) { string word; stream >> word; if (stream) { ++count; else { break; cout << count << " words" << endl; return 0; else { cout << "Invalid arguments" << endl; return -1;