ADVERTISEMENT
ADVERTISEMENT

Home » C++ programs » C++ basic programs

C++ program to read string using cin.getline()

Since cin does not read complete string using spaces, stings terminates as you input space. While cin.getline() – is used to read unformatted string (set of characters) from the standard input device (keyboard). This function reads complete string until a give delimiter or null match.

In this program will read details name, address, about of a person and print in different lines, name will contain spaces and dot, address will contain space, commas, and other special characters, same about will also contains mixed characters. We will read all details using cin.getline() function and print using cout.

cin.getline() example in C++.



/*C++ program to read string using cin.getline().*/
#include  <iostream>
using namespace std;
 
//macro definitions for maximum length of variables
#define MAX_NAME_LENGTH     50
#define MAX_ADDRESS_LENGTH  100
#define MAX_ABOUT_LENGTH    200
 
using namespace std;
 
int main()
{
    char name[MAX_NAME_LENGTH],address[MAX_ADDRESS_LENGTH],about[MAX_ABOUT_LENGTH];
 
    cout << "Enter name: ";
    cin.getline(name,MAX_NAME_LENGTH);
 
    cout << "Enter address: ";
    cin.getline(address,MAX_ADDRESS_LENGTH);
 
    cout << "Enter about yourself (press # to complete): ";
    cin.getline(about,MAX_ABOUT_LENGTH,'#');    //# is a delimiter 
 
    cout << "\nEntered details are:";
    cout << "Name: "  << name << endl;
    cout << "Address: " << address << endl;
    cout << "About: " << about << endl;
 
    return 0;
}

Output

    Enter name: Mr. Mike Thomas
    Enter address: 101, Phill Tower, N.S., USA
    Enter about yourself (press # to complete): Hello there!
    I am Mike, a website designer.
    My hobbies are creating web applications.#

    Entered details are:Name: Mr. Mike Thomas
    Address: 101, Phill Tower, N.S., USA
    About: Hello there!
    I am Mike, a website designer.
    My hobbies are creating web applications.
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.