cin using char type array

#include <iostream>
#include <conio.h>
#include <iomanip>

using namespace std;

int main(){
    int age  , years ;

    char name[20];

    cout <<"Enter your age in years: "<< endl;
    cin >> years;

    cout <<"Enter your name in years: " <<endl;
    cin >> name;
    age = years*12;
    cout << " Your age in months is: " << age <<endl;
    cout << "Your name is: "<< name <<endl;

    return 0;
}

There are two differences with your code:

cin << name;
(...)
cout << name << endl;

I’m assuming you thought

cout << “Enter your name” << name[15] << endl;

would make it ask for input. This is not what cout does. Cout prints out stuff on the console, it doesn’t ask for input. That’s cin‘s task.

Also you don’t put [15] after the array name, this would just print out the 15th character in your array, which would be a garbage character as long as the name entered does not reach a length of 15.

Leave a Comment