0

The code is simple. Yet, I'm confused about cin.getline() function. From my understanding of the following code, after the prompt "what is the message today?", the computer would wait for me to give an input. Yet, it is not like this.

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.

// C-string.cpp : using C strings //
-----------------------------------------------------------
#include <iostream> 
#include <iomanip>
#include <cstring>   // include header file cstring 

using namespace std; 
char header[] = "\n      *** C Strings ****** \n\n"; 
int main() 
{ 
    char hello[30] = "Hello", name[20], message[80];
    cout << header << "Your first name: ";
    cin >> setw(20) >> name;   
    strcat(hello, name);   
    cout << hello << endl;   
    cin.sync();   
    cout << "\n what is the message today?" << endl;   
    cin.getline(message, 80);   
    if (strlen(message)>0)   
    { 
        for (int i=0; message[i]!= '\0'; ++i)
            cout << message[i] << ' ';
        cout << endl; 
    }   
    return 0; 
}

output:

dev$:./a.out

      *** C Strings ****** 

Your first name: l Hellol

what is the message today? dev$:
NathanOliver
  • 150,499
  • 26
  • 240
  • 331
kkxx
  • 501
  • 4
  • 12

0 Answers0