C++ Revision Day-6

Photo by Ilya Pavlov on Unsplash

C++ Revision Day-6

1) How to input string in C++?

There are three ways to input a string, using cin, get, and getline. All three methods are mentioned in the sample program below.

#include <iostream>
using namespace std;

int main()
{
    char s[10];

    cout << "Enter a string: ";
    cin >> str;

    cout << "nEnter another string: ";
    cin.get(s, 10);

    getline(cin, str);

    return 0;
}

Summary of Differences:

  • cin: Reads formatted input, skips leading whitespace, stops at first whitespace after the input.

  • cin.get(): Reads a single character, including whitespace.

  • getline(): Reads an entire line of text, including spaces, and stops at the newline character.

2) How to get absolute value in C++?

In C++, there are three functions in the cstdlib header file to return the absolute value of the integer. Those are:

  • abs()

  • labs()

  • llabs()

  • For abs() its type int in C++.

  • For labs(), its type long int in C++

  • For llabs() its long long int in C++.

3) Outputs:-

  1.  // Assume that integers take 4 bytes. 
     #include<iostream> 
    
     using namespace std; 
    
     class Test 
     { 
     static int i; 
     int j; 
     }; 
    
     int Test::i; 
    
     int main() 
     { 
         cout << sizeof(Test); 
         return 0; 
     }
    

    output : 4
    static data members do not contribute in size of an object. So ‘i’ is not considered in size of Test. Also, all functions (static and non-static both) do not contribute in size.

  2.  #include<iostream> 
    
     using namespace std; 
     class Base1 { 
     public: 
         Base1() 
         { cout << " Base1's constructor called" << endl; } 
     }; 
    
     class Base2 { 
     public: 
         Base2() 
         { cout << "Base2's constructor called" << endl; } 
     }; 
    
     class Derived: public Base1, public Base2 { 
     public: 
         Derived() 
         { cout << "Derived's constructor called" << endl; } 
     }; 
    
     int main() 
     { 
     Derived d; 
     return 0; 
     }