Skip to main content
Engineering LibreTexts

11.2.1: C++ Input- More getline()

  • Page ID
    29099
  • getline() function and character array

    In C++, stream classes support line-oriented functions, getline() and write() to perform input and output functions respectively. getline() function reads whole line of text that ends with new line or until the maximum limit is reached. getline() is the member function of istream class and has the syntax:

    The function does the following operations:
    1. Extracts character up to the delimiter.
    2. Stores the characters in the buffer.
    3. Maximum number of characters extracted is size – 1.
    Note that the terminator(or delimiter) character can be any character (like ‘ ‘, ‘, ‘ or any special character, etc.). The terminator character is read but not saved into a buffer, instead it is replaced by the null character.

    // C++ program to show the getline() with 
    // character array 
    #include <iostream> 
    using namespace std; 
    
    int main() 
    { 
        char str[20]; 
        cout << "Enter Your Name::"; 
    
        // see the use of getline() with array str
        // will read until '\n' or 20 characters
        cin.getline(str, 20); 
    
        cout << "\nYour Name is:: " << str; 
        return 0; 
    } 
    

    Notice that the getline() function looks almost like a method of cin. This example does NOT use a delimiter...it is proper to use a delimiter if you desire.

    Input :

    Pat Mac 

    Output :

     Your Name is:: Pat Mac
    

    This code exhibits the write/put with cout. The cout.write will write out at most 9 characters. The cout.put will output a single character. 

    #include <iostream>
    using namespace std;
    
    int main()
    {
    	char myStr[] = "This is a string of characters that is over 20 characters long";
    	char mych = 'X';
    	
    	cout.write(myStr, 9);
    	cout << endl;
    	cout.put(mych);
    	
    	return 0;
    }

    When you run the code, the output will be:

    This is a
    X
    

    Adapted from:
    "getline() function and character array" by AdityaRakhechaGeeks for Geeks is licensed under CC BY-SA 4.0

    • Was this article helpful?