C++ program to print number and string entered by the user using class

Learn, how can we print number and string entered by the user using the class and object approach.
Submitted by Shubh Pachori, on September 09, 2022

Example:

Input:
Enter String : string
Enter Number : 123

Output:
String you entered : string
Number you entered : 123

C++ code to print number and string entered by the user using the class and object approach

#include <iostream>
using namespace std;

// create a class
class InputNumStr {
  // private data members
 private:
  long number;
  char str[30];

  // public member functions
 public:
  // getNumStr() function to insert 
  // string and number
  void getNumStr() {
    cout << "Enter String : ";
    cin.getline(str, 30);

    cout << "Enter Number : ";
    cin >> number;
  }

  // putNumStr() function to show inserted 
  // number and string
  void putNumStr() {
    cout << "String you entered : " << str << endl;
    cout << "Number you entered : " << number << endl;
  }
};

int main() {
  // create an object
  InputNumStr I;

  // calling getNumStr() function to 
  // insert number and string
  I.getNumStr();

  // calling putNumStr() function to show
  // inserted number and string
  I.putNumStr();

  return 0;
}

Output:

RUN 1:
Enter String : Hello world!
Enter Number : 108
String you entered : Hello world!
Number you entered : 108

RUN 2:
Enter String : Welcome at includehelp.com
Enter Number : 1008
String you entered : Welcome at includehelp.com
Number you entered : 1008

Explanation:

In the above code, we have created a class InputNumStr, one long type and one char type array data members number and str[30] to store the number and string, and public member functions getNumStr() and putNumStr() to store the number and string and to print number and string entered by the user.

In the main() function, we are creating an object I of class InputNumStr, inputting the number and string by the user using the getNumStr() function, and finally calling the putNumStr() member function to print number and string entered by the user. The putNumStr() function contains the logic to print the number and string that is entered by the user.

C++ Class and Object Programs (Set 2) »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.