Download presentation
Presentation is loading. Please wait.
1
CS150 Introduction to Computer Science 1
Example Write a program to read five integer numbers from a file, and calculate the sum. Whenever you pass an ifstream or ofstream variable to a function, you must pass it by reference (i.e. &). Why? 4/5/2019 CS150 Introduction to Computer Science 1
2
CS150 Introduction to Computer Science 1
Ch. 7 Data Types We’ve seen: ints: typically 32 bits, can be 16 floats: typically 32 bits chars: typically 8 bits New: short: typically 16 bits long: typically 64 bits double: typically 64 bits System dependent Look at climit and cfloat on p. 350 4/5/2019 CS150 Introduction to Computer Science 1
3
CS150 Introduction to Computer Science 1
Characters Characters stored in one byte Represented by ASCII value American Standard Code for Information Interchange Characters are stored as an 8 bit int Relationships ‘0’ < ‘1’ < ‘2’ < ‘3’ < ‘4’ < ‘5’ < ‘6’ < ‘7’ < ‘8’ < ‘9’ 4/5/2019 CS150 Introduction to Computer Science 1
4
CS150 Introduction to Computer Science 1
Program The printable characters have ASCII values in the range of 32 to 126. Write a C++ program segment that will print the printable character and its associated ASCII value 8 values per line. 4/5/2019 CS150 Introduction to Computer Science 1
5
CS150 Introduction to Computer Science 1
Type Casting There are two ways to perform type casting cout << (int) ‘a’; Cout << int(‘a’); 4/5/2019 CS150 Introduction to Computer Science 1
6
CS150 Introduction to Computer Science 1
What is the Output? int(‘d’)-int(‘a’) char((int(‘M’) – int(‘A’)) + int(‘a’)) int(‘7’) – int(‘0’) char(int(‘5’) + 1) 4/5/2019 CS150 Introduction to Computer Science 1
7
CS150 Introduction to Computer Science 1
Char Operations Useful operations: islower, toupper, isdigit, islower, isspace, isupper, tolower #include <ctype> void todigit(char, &int); … void todigit(char ch, &int num) { if (isdigit(ch)) num = int(ch) - int (‘0’); } 4/5/2019 CS150 Introduction to Computer Science 1
8
CS150 Introduction to Computer Science 1
Char I/O Operations Using cin, can we read in all possible chars? We need some other operations 4/5/2019 CS150 Introduction to Computer Science 1
9
CS150 Introduction to Computer Science 1
Program #include <iostream> int main() { char ch; int count; count = 0; cin.get(ch); while (!cin.eof()) count++; } cout << "Number of characters = " << count << endl; 4/5/2019 CS150 Introduction to Computer Science 1
10
CS150 Introduction to Computer Science 1
Program #include <iostream> int main() { char ch; cin.get(ch); while (!cin.eof()) cout.put(ch); } 4/5/2019 CS150 Introduction to Computer Science 1
11
CS150 Introduction to Computer Science 1
Program #include <iostream> int main() { const char newline = '\n'; char ch; cin.get(ch); while (ch != newline && !cin.eof()) cout.put(ch); } cout.put(newline); 4/5/2019 CS150 Introduction to Computer Science 1
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.