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) »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.