Presentation is loading. Please wait.

Presentation is loading. Please wait.

Do you know the syntax for each of these, used to read and write to data files?  Pointers: think of it as the memory address of the file  fopen() 

Similar presentations


Presentation on theme: "Do you know the syntax for each of these, used to read and write to data files?  Pointers: think of it as the memory address of the file  fopen() "— Presentation transcript:

1

2 Do you know the syntax for each of these, used to read and write to data files?  Pointers: think of it as the memory address of the file  fopen()  fclose()  fscanf()  fprintf()

3  fopen() returns a FILE pointer back to the pRead variable #include Main() { FILE *pRead; pRead = fopen(“file1.dat”, “r”); if(pRead == NULL) printf(“\nFile cannot be opened\n”); else printf(“\nFile opened for reading\n”); }

4

5  Pretty basic.

6  Reads a single field from a data file  “%s” will read a series of characters until a white space is found  can do fscanf(pRead, “%s%s”, name, hobby);

7 #include Main() { FILE *pRead; char name[10]; pRead = fopen(“names.dat”, “r”); if( pRead == NULL ) printf( “\nFile cannot be opened\n”); else printf(“\nContents of names.dat\n”); fscanf( pRead, “%s”, name ); while( !feof(pRead) ) { printf( “%s\n”, name ); fscanf( pRead, “%s”, name ); }

8 Kelly11/12/866Louisville Allen04/05/7749Atlanta Chelsea03/30/9012Charleston Can you write a program that prints out the contents of this information.dat file?

9 #include Main() { FILE *pRead; char name[10]; char birthdate[9]; float number; char hometown[20]; pRead = fopen(“information.dat”, “r”); if( pRead == NULL ) printf( “\nFile cannot be opened\n”); else fscanf( pRead, “%s\t%s\t%f\t%s”, name, birthdate, &number, hometown ); while( !feof(pRead) ) { printf( “%s \t %s \t %f \t %s\n”, name, birthdate, &number, hometown ); fscanf(pRead,“%s\t%s\t%f\t%s”, name, birthdate, &number, hometown ); }

10  The fprintf() function sends information (the arguments) according to the specified format to the file indicated by stream. fprintf() works just like printf() as far as the format goes. printf()

11 #include Main() { FILE *pWrite; char fName[20]; char lName [20]; float gpa; pWrite = fopen(“students.dat”,”w”); if( pWrite == NULL ) printf(“\nFile not opened\n”); else printf(“\nEnter first name, last name, and GPA separated” printf(“Enter data separated by tabs:”); scanf(“%s\t%s\t%f”, fName, lName, &gpa); fprintf(pWrite, “%s \t %s \t %.2f \n”, fName, lName, gpa); fclose(pWrite); }

12  Can you write a program that asks the user for their  Name  Phone Number  Bank account balance And then prints this information to a data file called accounts.dat ?

13  Summary  Include #include directive at beginning of program  Use cin to take data from user  Use cout to display data on screen ▪ Display multiple strings and integers in the same cout statement by separating items with <<

14 #include using namespace std; string name = “”; int main(void) { cout<<“What is your name?”; cin>>name; cout<<endl<<“Hello”<<name.c_str(); return 0; }

15 #include using namespace std; int x = 25; string str2 = “This is a test”; int main( void ) { cout<<“Test”<<1<<2<<“3”; cout<<25 %7<<endl<<str2.c_str(); return 0; }

16 Test 1234 This is a test

17  How a computer stores data in its internal memory  RAM (Random-Access Memory) - temporary  ROM (Read-Only Memory) – non volatile  Store data in bytes  How you store data temporarily  Create variables based on fundamental types (bool, char, int, float)  constants: #define CONSTNAME value  sizeof()

18 TYPESIZEVALUES bool1 bytetrue (1) or false (0) char1 byte‘a’ to‘z’, ‘A’ to ‘Z’, ‘0’ to ‘9’, space, tab, and so on int4 bytes-2,147,483,648 to 2,147,483,647 short2 bytes-32,768 to 32,767 long4 bytes-2,147,483,648 to 2,147,483,647 float4 bytes+ - (1.2 x 10^-38 to 3.4 x 10^38) double8 bytes+- (2.3 x 10^-308 to -1.7 x 10^308)

19  What do each of the following evaluate to? 1. long X= 8; int Y= 8; if(X==Y) //true or false? if(X!=0) //true or false? 2. int X= 4; int Y= 5; if(Y > (2/3)) //true or false? 3. if(0 < x < 99) //true or false? 4. if(0<= (0<1))//true or false?

20  What do each of the following evaluate to? 1. long X= 8; int Y= 8; if(X==Y) //true if(X!=0) //true 2. int X= 4; int Y= 5; if(Y > (2/3)) //true 3. if(0 < x < 99) //true …TRUE (1) and FALSE (0) < 99 4. if(0<= (0<1))//true

21  if(condition) statement; else if (condition) statement;  condition ? expr1 : expr2  ex. z = ( x > y ) ? y : x ;  cannot do (x>y) ? count << “x is greater than y.” : cout << “x isn’t greater than y.”

22 switch(expression){ case expr1: statement; break; case expr2: statement; break; case expr3: statement; break; default: statements break; }

23  while (condition) { statements; }  do { statements; } while(condition);

24  for (initialization; condition; expression) { statements; }  Incrementing: Prefix and Postfix int x = 5; int y = 6; int z = y++ //z=6, y=7 postfix operator int z = ++x //z=6, x=6 prefix operator

25 KeywordPurpose breakExits the nearest enclosing “switch” statement or iteration statement continueStarts the next loop of the nearest enclosing iteration statement gotoJumps to a particular place in your code returnEnds a function and returns a value

26  Can you write a program that prints out the following? 0 1 2 3 4 5 6 7 8 9

27 for ( int count = 0; count < 10; count ++) { cout <<count<<“”; }

28 1. Write a conditional statement that will assign x/y to x if y doesn’t equal 0. 2. Write a while loop that calculates the summative of positive integers from 1 to some number n. 3. Write a conditional statement that assigns x*y if x is even; otherwise, if x is odd and y doesn’t equal 0, assign x to x/y; if neither of the preceding cases is true, output to the screen that y is equal to 0.

29  Function declaration  Function definition  Function call

30 #include using namespace std; int add(int a, int b); int main(void) { int number1, number2; cout << “Enter the first value to be summed:”’ cin >> number1; cout << “\nEnter the second:”; cin >> number2; cout << “\n The sum is: “ << add (number1, number2) <<endl; } int add(int a, int b) { return a+b; }

31  Write a function, called multiply that multiplies two numbers and returns the result

32  Declare classes  Create objects  3 MAIN PRINCIPLES OF OOP  Data abstraction – hiding data members and implementation of a class behind an interface so that the user of the class corrupt that data  Encapsulation – each class represents a specific thing or concept. Multiple classes combine to produce the whole  Polymorphism-objects can be used in more than one program

33  Classes are general models from which you can create objects  Classes have data members either data types or methods  Classes should contain a constructor method and a destructor method  See handout for example of a program that utilizes a class

34 class ClassName { memberList }; memberList can be either data member declarations or method declarations

35 Class Bow { //data member declarations string color; bool drawn; int numOfArrows; Bow(string aColor); //constructor ~Bow(); //destructor //methods void draw(); int fire(); };

36 Return_type ClassName::methodName(argumentList) { methodImplementation }

37 //draws the bow Void Bow::draw() { drawn = true; cout<< “The “<<color<<“bow has been drawn.”<<endl; }

38  Arrays  Pointers

39  data_type array_name [number-of-elements];  Two Dimensional Array array_type array_name [number_ofelements1][number_of_elements2];

40  type* pointer_name;  ex. int my_int; int* my_int_pointer = &my_int; Assigns the address of my_int to the pointer

41  Can you write a program using C++ that uses a FOR loop to initialize a 2D array that looks like the following {0,5,10,15}{0,2,4,6}

42  Used to create functions, classes, and variables of the same name  Ex. Namespace combat { void fire() } Namespace exploration { void fire() }

43 class aClass// Base class { public: int anInt; } class aDerivedClass : public aClass//Derived class { protected: float aFloat; };

44 #include enum BREED { YORKIE, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB }; class Mammal{ public: Mammal(); // constructors ~Mammal();//destructor //accessors int GetAge()const; void SetAge(int); int GetWeight() const; void SetWeight(); //Other methods void Speak(); void Sleep(); protected: int itsAge; int itsWeight; }; class Dog : public Mammal { public: Dog(); // Constructors ~Dog(); // Accessors BREED GetBreed() const; void SetBreed(BREED); // Other methods // WagTail(); // BegForFood(); protected: BREED itsBreed; }; Animals MammalsReptiles HorseDog HoundTerrier YorkieCairn

45  Private members are not available to derived classes. You could make itsAge and itsWeight public, but that is not desirable. You don't want other classes accessing these data members directly.  What you want is a designation that says, "Make these visible to this class and to classes that derive from this class." That designation is protected. Protected data members and functions are fully visible to derived classes, but are otherwise private.

46  When do we need to override functions?  If you are a programmer example.  If we consider “Woof” of the dog as speak.  When a derived class creates a function with the same return type and signature as a member function in the base class, but with a new implementation, it is said to be overriding that method.

47  #include  enum BREED { YORKIE, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB };  class Mammal {  public:  // constructors  Mammal() { cout << "Mammal constructor...\n"; }  ~Mammal() { cout << "Mammal destructor...\n"; }  //Other methods  void Speak()const { cout << "Mammal sound!\n"; }  void Sleep()const { cout << "shhh. I'm sleeping.\n"; }  protected:  int itsAge;  int itsWeight;  };  class Dog : public Mammal {  public:  // Constructors  Dog(){ cout << "Dog constructor...\n"; }  ~Dog(){ cout << "Dog destructor...\n"; }  // Other methods  void WagTail() { cout << "Tail wagging...\n"; }  void BegForFood() { cout << "Begging for food...\n"; }  void Speak()const { cout << "Woof!\n"; }  private:  BREED itsBreed;  };  int main() {  Mammal bigAnimal;  Dog fido;  bigAnimal.Speak();  fido.Speak();  getchar();  return 0;  }

48  When you overload a method, you create more than one method with the same name, but with a different signature. When you override a method, you create a method in a derived class with the same name as a method in the base class and the same signature.

49 #include int area(int x); // square area int area(int x,int y); //triangle area float area(int x,int y, int radius); //circle area int main(){ int x=4, y=5, rad=3; cout<<"The Square area is :"<<area(x); cout<<"\nThe Triangle area is :"<<area(x,y); cout<<"\nThe Circle area is :"<<area(x,y,rad); getchar(); return 0; } int area(int x) // square area { return x*x; } int area(int x,int y ) //triangle area { return x*y; } float area(int x,int y, int radius) //circle area { return radius*radius*3.14; } Output: The Square area is: 16 The Triangle area is :20 The Circle area is: 28.26

50 #include class Mammal { public: void Move() const { cout << "Mammal move one step\n"; } void Move(int distance) const { cout << "Mammal move "; cout << distance <<" _steps.\n"; } protected: int itsAge; int itsWeight; }; class Dog : public Mammal { public: // You may receive a warning that you are hiding a function! void Move() const { cout << "Dog move 5 steps.\n"; } }; int main() { Mammal bigAnimal; Dog fido; bigAnimal.Move(); bigAnimal.Move(2); fido.Move(8);// can I do this? fido.Move(); return 0; } Output: Mammal move one step Mammal move 2 steps. Dog move 5 steps

51  To call a function you’ve overridden in a derived class you need to use the keyword virtual.  Example: struct Base { virtual void do_something() = 0; }; struct Derived1 : public Base { void do_something() { cout << "I'm doing something"; } }; struct Derived2 : public Base { void do_something() { cout << "I'm doing something else"; } }; int main() { Base *pBase = new Derived1; pBase->do_something();//does something delete pBase; pBase = new Derived2; pBase->do_something();//does something else delete pBase; return 0; }

52 Output: (1)dog (2)cat (3)horse (4)pig: 1 (1)dog (2)cat (3)horse (4)pig: 2 (1)dog (2)cat (3)horse (4)pig: 3 (1)dog (2)cat (3)horse (4)pig: 4 (1)dog (2)cat (3)horse (4)pig: 5 Woof! Meow! Winnie! Oink! Mammal speak! #include class Mammal { public: Mammal():itsAge(1) { } ~Mammal() { } virtual void Speak() const { cout << "Mammal speak!\n"; } protected: int itsAge; }; class Dog : public Mammal { public: void Speak()const { cout << "Woof!\n"; } }; class Cat : public Mammal { public: void Speak()const { cout << "Meow!\n"; } }; class Horse : public Mammal { public: void Speak()const { cout << "Winnie!\n"; } }; class Pig : public Mammal { public: void Speak()const { cout << "Oink!\n"; } }; int main() { Mammal* theArray[5]; Mammal* ptr; int choice, i; for ( i = 0; i<5; i++) { cout << "(1)dog (2)cat (3)horse (4)pig: "; cin >> choice; switch (choice) { case 1: ptr = new Dog; break; case 2: ptr = new Cat; break; case 3: ptr = new Horse; break; case 4: ptr = new Pig; break; default: ptr = new Mammal; break; } theArray[i] = ptr; } for (i=0;i<5;i++) theArray[i]->Speak(); system("pause"); return 0; }

53  Only if you have to redefine a function in a Derived class that is already defined in Base Class.

54  Used in place of a specific data type. For example, use a template to add data types together, whichever data type the user wishes (i.e. integers, floats)

55  Good Read: http://www.cplusplus.com/doc/tutorial/te mplates/

56 QUESTIONS?


Download ppt "Do you know the syntax for each of these, used to read and write to data files?  Pointers: think of it as the memory address of the file  fopen() "

Similar presentations


Ads by Google