Author: saqibkhan

  • Write a Program to Remove Spaces From a String

    C++// C++ Program to remove spaces from a string #include <iostream> #include <string> using namespace std; string remove_spaces(string str) { string result = ""; for (char c : str) { if (c != ' ') { result += c; } } return result; } int main() { string str = "Gfg to the moon"; cout << "Without spaces: " << remove_spaces(str) << endl; return 0; }

    Output

    Without spaces: Gfgtothemoon
  • Write a Program to Remove All Characters From a String Except Alphabets

    C++// C++ Programto remove all characters from a string except // alphabets #include <cctype> #include <iostream> #include <string> using namespace std; string remove_non_alphabets(string str) { string result = ""; for (char c : str) { if (isalpha(c)) { result += c; } } return result; } int main() { string str = "Gee$ksfor$geeks"; cout << "Alphabets only: " << remove_non_alphabets(str) << endl; return 0; }

    Output

    Alphabets only: Geeksforgeeks
  • Write a Program to Remove the Vowels from a String

    C++// C++ Program to remove the vowels from a string #include <cstring> #include <iostream> using namespace std; int main() { int j = 0; string str = "GeeksforGeeks"; for (int i = 0; str[i] != '\0'; i++) { if (str[i] != 'a' && str[i] != 'e' && str[i] != 'i' && str[i] != 'o' && str[i] != 'u' && str[i] != 'A' && str[i] != 'E' && str[i] != 'I' && str[i] != 'O' && str[i] != 'U') { str[j++] = str[i]; } } while (j < str.size()) { str[j] = '\0'; j++; } cout << "String without vowels: " << str << endl; return 0; }

    Output

    String without vowels: GksfrGks
  • Files and Streams

    So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively.

    This tutorial will teach you how to read and write from a file. This requires another standard C++ library called fstream, which defines three new data types −

    Sr.NoData Type & Description
    1ofstreamThis data type represents the output file stream and is used to create files and to write information to files.
    2ifstreamThis data type represents the input file stream and is used to read information from files.
    3fstreamThis data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.

    To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.

    Opening a File

    A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.

    Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.

    voidopen(constchar*filename, ios::openmode mode);

    Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened.

    Sr.NoMode Flag & Description
    1ios::appAppend mode. All output to that file to be appended to the end.
    2ios::ateOpen a file for output and move the read/write control to the end of the file.
    3ios::inOpen a file for reading.
    4ios::outOpen a file for writing.
    5ios::truncIf the file already exists, its contents will be truncated before opening the file.

    You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case that already exists, following will be the syntax −

    ofstream outfile;
    outfile.open("file.dat", ios::out | ios::trunc );

    Similar way, you can open a file for reading and writing purpose as follows −

    fstream  afile;
    afile.open("file.dat", ios::out | ios::in );

    Closing a File

    When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination.

    Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.

    voidclose();

    Writing to a File

    While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object.

    Reading from a File

    You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object.

    Read and Write Example

    Following is the C++ program which opens a file in reading and writing mode. After writing information entered by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen −

    #include <fstream>#include <iostream>usingnamespace std;intmain(){char data[100];// open a file in write mode.
       ofstream outfile;
       outfile.open("afile.dat");
    
       cout <<"Writing to the file"<< endl;
       cout <<"Enter your name: "; 
       cin.getline(data,100);// write inputted data into the file.
       outfile << data << endl;
    
       cout <<"Enter your age: "; 
       cin >> data;
       cin.ignore();// again write inputted data into the file.
       outfile << data << endl;// close the opened file.
       outfile.close();// open a file in read mode.
       ifstream infile; 
       infile.open("afile.dat"); 
     
       cout <<"Reading from the file"<< endl; 
       infile >> data;// write the data at the screen.
       cout << data << endl;// again read the data from the file and display it.
       infile >> data; 
       cout << data << endl;// close the opened file.
       infile.close();return0;}

    When the above code is compiled and executed, it produces the following sample input and output −

    $./a.out
    Writing to the file
    Enter your name: Zara
    Enter your age: 9
    Reading from the file
    Zara
    9
    

    Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement.

    File Position Pointers

    Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg (“seek get”) for istream and seekp (“seek put”) for ostream.

    The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream.

    The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file’s starting location. Some examples of positioning the “get” file-position pointer are −

    // position to the nth byte of fileObject (assumes ios::beg)
    fileObject.seekg( n );// position n bytes forward in fileObject
    fileObject.seekg( n, ios::cur );// position n bytes back from end of fileObject
    fileObject.seekg( n, ios::end );// position at end of fileObject
    fileObject.seekg(0, ios::end );
  • Write a Program to Count the Number of Vowels 

    C++// C++ Program to count the number of vowels #include <cstring> #include <iostream> using namespace std; int main() { string str = "GeeksforGeeks to the moon"; int vowels = 0; for (int i = 0; str[i] != '\0'; i++) { if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' || str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') { vowels++; } } cout << "Number of vowels in the string: " << vowels << endl; return 0; }

    Output

    Number of vowels in the string: 9
  • Interfaces in C++ (Abstract Classes)

    An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class.

    The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation details separate from associated data.

    A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual function is specified by placing “= 0” in its declaration as follows −

    class Box {
       public:
    
      // pure virtual function
      virtual double getVolume() = 0;
      
    private:
      double length;      // Length of a box
      double breadth;     // Breadth of a box
      double height;      // Height of a box
    };

    The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error.

    Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error.

    Classes that can be used to instantiate objects are called concrete classes.

    Abstract Class Example

    Consider the following example where parent class provides an interface to the base class to implement a function called getArea() −

    #include <iostream>
     
    using namespace std;
     
    // Base class
    class Shape {
       public:
    
      // pure virtual function providing interface framework.
      virtual int getArea() = 0;
      void setWidth(int w) {
         width = w;
      }
      void setHeight(int h) {
         height = h;
      }
    protected:
      int width;
      int height;
    }; // Derived classes class Rectangle: public Shape { public:
      int getArea() { 
         return (width * height); 
      }
    }; class Triangle: public Shape { public:
      int getArea() { 
         return (width * height)/2; 
      }
    }; int main(void) { Rectangle Rect; Triangle Tri; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout << "Total Rectangle area: " << Rect.getArea() << endl; Tri.setWidth(5); Tri.setHeight(7); // Print the area of the object. cout << "Total Triangle area: " << Tri.getArea() << endl; return 0; }

    When the above code is compiled and executed, it produces the following result −

    Total Rectangle area: 35
    Total Triangle area: 17
    

    You can see how an abstract class defined an interface in terms of getArea() and two other classes implemented same function but with different algorithm to calculate the area specific to the shape.

    Designing Strategy

    An object-oriented system might use an abstract base class to provide a common and standardized interface appropriate for all the external applications. Then, through inheritance from that abstract base class, derived classes are formed that operate similarly.

    The capabilities (i.e., the public functions) offered by the external applications are provided as pure virtual functions in the abstract base class. The implementations of these pure virtual functions are provided in the derived classes that correspond to the specific types of the application.

    This architecture also allows new applications to be added to a system easily, even after the system has been defined.

  • Write a Program to Toggle Each Character in a String 

    C++// C++ Program to toggle string #include <cstring> #include <iostream> using namespace std; int main() { string str = "GeeksforGeeks"; for (int i = 0; str[i] != '\0'; i++) { if (islower(str[i])) { str[i] = toupper(str[i]); } else if (isupper(str[i])) { str[i] = tolower(str[i]); } } cout << "Toggled string: " << str << endl; return 0; }

    Output

    Toggled string: gEEKSFORgEEKS

  • Data Encapsulation in C++

    All C++ programs are composed of the following two fundamental elements −

    • Program statements (code) − This is the part of a program that performs actions and they are called functions.
    • Program data − The data is the information of the program which gets affected by the program functions.

    Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.

    Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.

    C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and public members. By default, all items defined in a class are private. For example −

    class Box {
       public:
    
      double getVolume(void) {
         return length * breadth * height;
      }
    private:
      double length;      // Length of a box
      double breadth;     // Breadth of a box
      double height;      // Height of a box
    };

    The variables length, breadth, and height are private. This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulation is achieved.

    To make parts of a class public (i.e., accessible to other parts of your program), you must declare them after the public keyword. All variables or functions defined after the public specifier are accessible by all other functions in your program.

    Making one class a friend of another exposes the implementation details and reduces encapsulation. The ideal is to keep as many of the details of each class hidden from all other classes as possible.

    Data Encapsulation Example

    Any C++ program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Consider the following example −

    #include <iostream>
    using namespace std;
    
    class Adder {
       public:
    
      // constructor
      Adder(int i = 0) {
         total = i;
      }
      
      // interface to outside world
      void addNum(int number) {
         total += number;
      }
      
      // interface to outside world
      int getTotal() {
         return total;
      };
    private:
      // hidden data from outside world
      int total;
    }; int main() { Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout << "Total " << a.getTotal() <<endl; return 0; }

    When the above code is compiled and executed, it produces the following result −

    Total 60
    

    Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly.

    Designing Strategy

    Most of us have learnt to make class members private by default unless we really need to expose them. That’s just good encapsulation.

    This is applied most frequently to data members, but it applies equally to all members, including virtual functions.

  • Write a Program to Find the Length of the String Without using strlen() Function 

    C++// C++ Program to find the length of a string without using // strlen() #include <cstring> #include <iostream> using namespace std; int main() { string str = "GeeksforGeeks"; int length = 0; for (int i = 0; str[i] != '\0'; i++) { length++; } cout << "The length of the string is: " << length << endl; return 0; }

    Output

    The length of the string is: 13
  • Write a Program to Print Check Whether a Character is an Alphabet or Not

    C++// C++ program to print whether a character is an alphabet // or not #include <cctype> #include <iostream> using namespace std; int main() { char ch; ch = 'a'; if (isalpha(ch)) { cout << ch << " is an alphabet." << endl; } else { cout << ch << " is not an alphabet." << endl; } return 0; }

    Output

    a is an alphabet.