CSE 332: C++ data types, input, and output Built-In (a.k.a. Native) Types in C++ int, long, short, char (signed, integer division) –unsigned versions too.

Slides:



Advertisements
Similar presentations
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Advertisements

1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
1 File I/O In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
C++ crash course Class 3 designing C++ programs, classes, control structures.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
C++ Programming Language Day 1. What this course covers Day 1 – Structure of C++ program – Basic data types – Standard input, output streams – Selection.
Stream Handling Streams - means flow of data to and from program variables. - We declare the variables in our C++ for holding data temporarily in the memory.
Data Structures Using C++ 2E
Working with Strings Lecture 2 Hartmut Kaiser
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
1 C++ Syntax and Semantics, and the Program Development Process.
C++ Streams Lecture-2.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
File I/O ifstreams and ofstreams Sections 11.1 &
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Operator Overloading Operator Overloading allows a programmer to define new uses of the existing C/C++ operator symbols. –useful for defining common operations.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Monday, Mar 31, 2003Kate Gregory with material from Deitel and Deitel Week 12 Labs 4 and 5 are back File IO Looking ahead to the final.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
Copyright 2008 Oxford Consulting, Ltd 1 October C to C++ C++ Comments Can use the symbol // To identify single line comments.
C++ Programming Part 2 Michael Griffiths Corporate Information and Computing Services The University of Sheffield
FILE I/O IN C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
CSE 332: C++ IO We’ve Looked at Basic Input and Output Already How to move data into and out of a program –Using argc and argv to pass command line args.
1 I/O  C++ has no built-in support for input/output input/output is a library (iostream)  C++ program views input and output as a stream of bytes  Input:
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
1 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Managers and “mentors” identified on projects page. All member accounts created and projects populated.
Why Use Namespaces? Classes encapsulate behavior (methods) and state (member data) behind an interface Structs are similar, but with state accessible Classes.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Object-Oriented Programming (OOP) and C++
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
C++ Functions A bit of review (things we’ve covered so far)
CS212: Object Oriented Analysis and Design
Hank Childs, University of Oregon
Examples (D. Schmidt et al)
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ (Extensions to C)
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Motivation and Overview
Working with Strings Lecture 2 Hartmut Kaiser
Student Book An Introduction
Built-In (a.k.a. Native) Types in C++
Working with Strings Lecture 2 Hartmut Kaiser
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Variables, Identifiers, Assignments, Input/Output
Why Use Namespaces? Classes encapsulate behavior (methods) and state (member data) behind an interface Structs are similar, but with state accessible Classes.
Introduction to C++ Programming
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Today’s Objectives 28-Jun-2006 Announcements
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Presentation transcript:

CSE 332: C++ data types, input, and output Built-In (a.k.a. Native) Types in C++ int, long, short, char (signed, integer division) –unsigned versions too unsigned int, unsigned long, etc. –C++ guarantees a char is one byte in size –Sizes of other types are platform dependent –Can determine using sizeof(), INT_MAX float, double (floating point division) –More expensive in space and time –Useful when you need to describe continuous quantities bool type –Logic type, takes on values true, false

CSE 332: C++ data types, input, and output User (& Library) DefinedTypes in C++ enumerations enum primary_color {red, blue, yellow}; functions and operators –For example, things called from main function structs and classes –Similar abstractions in C++, extend C structs

CSE 332: C++ data types, input, and output Comparing C++ Classes and Structs struct My_Data { My_Data (int i) : x_(i) {} int x_; }; class My_Object { public: My_Object (); ~My_Object (); private: int y_; }; Struct members are public by default Class members are private by default Both can have –Constructors –Destructors –Member variables –Member functions Common practice: –use structs for data –use classes for objects with non-trivial methods

CSE 332: C++ data types, input, and output More About Both Native and User Types Pointers –raw memory address of an object or variable –its type constrains what types it can point to (more later) –can take on a value of 0 (not pointing to anything) References –“alias” for an object or variable –its type constrains what types it can refer to (more later) –cannot be 0 (always references something else) Mutable (default) vs. const types (read right to left) const int i; // read-only declaration int j; // readable and writable declaration

CSE 332: C++ data types, input, and output Scopes in C++ Each symbol is associated with a scope –The entire program (global scope) –A namespace (namespace scope) –Members of a class (class scope) –A function (function scope) –A block (block scope) A symbol is only visible within its scope –Helps hide unneeded details (abstraction) –Helps prevent symbol conflicts (encapsulation)

CSE 332: C++ data types, input, and output Why Use Namespaces? Classes encapsulate behavior (methods) and state (member data) behind an interface Structs are similar, but with state accessible Classes and structs are used to specify self- contained, cohesive abstractions –Can say what class/struct does in one sentence What if we want to describe more loosely related collections of state and behavior? Could use a class or struct –But that dilutes their design intent

CSE 332: C++ data types, input, and output Namespaces C++ offers an appropriate scoping mechanism for loosely related aggregates: Namespaces –Good for large function collections E.g., a set of related algorithms and function objects –Good for general purpose collections E.g., program utilities, performance statistics, etc. Declarative region –Where a variable/function can be declared Potential scope –Where a variable/function can be used –From where declared to end of declarative region

CSE 332: C++ data types, input, and output Namespace Properties Declared/(re)opened with namespace keyword namespace Foo {int baz_;} namespace Foo {int fxn() {return baz_;}} Access members using scoping operator :: std::cout << “hello world!” << std::endl; Everything not declared in another namespace is in the global (program-wide) namespace Can nest namespace declarations namespace Foo {namespace Err {…}}

CSE 332: C++ data types, input, and output Using Namespaces The using keyword makes elements visible –Only applies to the current scope Can add entire namespace to current scope using namespace std; cout << “hello, world!” << endl; Can introduce elements selectively using std::cout; cout << “hello, world!” << std::endl; Can also declare unnamed namespaces –Elements are visible after the declaration namespace {int i_; // i_ is now visible }

CSE 332: C++ data types, input, and output C++ string Class #include using namespace std; int main (int, char*[]) { string s; // empty s = “”; // empty s = “hello”; s += “, ”; s = s + “world!”; cout << s << endl; // prints: hello, world! return 0; } header file Various constructors Assignment operator Overloaded operators += + = == [] The last one is really useful: indexes string if (s[0] == ‘h’) …

CSE 332: C++ data types, input, and output Using C++ vs. C-style Strings #include using namespace std; int main (int, char*[]) { char * w = “world”; string sw = “world”; char * h = “hello, ”; string sh = “hello, ”; cout << (h < w) << endl; // 0: why? cout << (sh < sw) << endl; // 1:why? h += w; // illegal: why? sh += sw; cout << h << endl; cout << sh << endl; return 0; } C-style strings are contiguous arrays of char –Often accessed through pointers to char ( char * ) C++ string class (template) provides a rich set of overloaded operators Often C++ strings do “what you would expect” as a programmer Often C-style strings do “what you would expect” as a machine designer Suggestion: use C++ style strings any time you need to change, concatenate, etc.

CSE 332: C++ data types, input, and output C++ Input/Output Stream Classes #include using namespace std; int main (int, char*[]) { int i; // cout == std ostream cout << “how many?” << endl; // cin == std istream cin >> i; cout << “You said ” << i << “.” << endl; return 0; } header file –Use istream for input –Use ostream for output Overloaded operators << ostream insertion operator >> istream extraction operator Other methods –ostream: write, put –istream: get, eof, good, clear Stream manipulators –ostream: flush, endl, setwidth, setprecision, hex, boolalpha

CSE 332: C++ data types, input, and output C++ File I/O Stream Classes #include using namespace std; int main () { ifstream ifs; ifs.open (“in.txt”); ofstream ofs (“out.txt”); if (ifs.is_open () && ofs.is_open ()) { int i; ifs >> i; ofs << i; } ifs.close (); ofs.close (); return 0; } header file –Use ifstream for input –Use ofstream for output Other methods –open, is_open, close –getline –seekg, seekp File modes –in, out, ate, app, trunc, binary

CSE 332: C++ data types, input, and output C++ String Stream Classes #include using namespace std; int main (int, char*[]) { ifstream ifs (“in.txt”); if (ifs.is_open ()) { string line_1, word_1; getline (ifs, line_1); istringstream iss (line_1); iss >> word_1; cout << word_1 << endl; } return 0; } header file –Use istringstream for input –Use ostringstream for output Useful for scanning input –Get a line from file into string –Wrap string in a stream –Pull words off the stream Useful for formatting output –Use string as format buffer –Wrap string in a stream –Push formatted values into stream –Output formatted string to file

CSE 332: C++ data types, input, and output Using C++ String Stream Classes #include using namespace std; int main (int argc, char *argv[]) { if (argc < 3) return 1; ostringstream argsout; argsout << argv[1] << “ ” << argv[2]; istringstream argsin (argsout.str()); float f,g; argsin >> f; argsin >> g; cout << f << “ / ” << g << “ is ” << f/g << endl; return 0; } Program gets arguments as C-style strings But let’s say we wanted to input floating point values from the command line Formatting is tedious and error-prone in C-style strings ( sprintf etc.) iostream formatting is friendly Can we get there from here?

CSE 332: C++ data types, input, and output Storing Other Data Types Than char There are many options to store non-char data in C++ –Differ in complexity, ease of use Native C-style arrays –Can not add or remove positions –Can index positions directly –Not necessarily zero-terminated (why?) STL list container (bi-linked list) –Add/remove positions on either end –Cannot index positions directly STL vector container (“back stack”) –Can add/remove positions at the back –Can index positions directly X X X

CSE 332: C++ data types, input, and output A Quick Look at Vectors Goals –Give you a good basic data structure to use for now –Cover its correct usage –Start understanding why Vectors: nicer than arrays –Less to manage/remember –Harder to get things wrong (but still need to be careful) Example to the left prints v[0] is 1 v[1] is 2 v[2] is 4 #include using namespace std; int main (int, char *[]) { vector v; // This would be asking for trouble.... // v[0] = 1; v[1] = 2; v[2] = 4; //... but this works fine... v.push_back (1); v.push_back (2); v.push_back (4); //... and now this is ok... for (size_t s = 0; s < v.size(); ++s) { cout << "v[" << s << "] is " << v[s] << endl; } return 0; }