Pejman Moghadam / C-programming

C++ - cin example

Public domain


// ask for a person's name, and greet the person
#include <iostream>
#include <string>

int main()
{
    // ask for the person's name
    std::cout << "Please enter your first name: ";

    // read the name
    std::string name;         // define name
    std::cin >> name;         // read one word into name

    // write a greeting
    std::cout << "Hello, " << name << "!" << std::endl;
    return 0;
}

Output :

Please enter your first name: Pejman
Hello, Pejman!

// ask for a person's name, and generate a framed greeting
#include <iostream>
#include <string>

int main()
{
    std::cout << "Please enter your first name: ";
    std::string name;
    std::cin >> name;

    // build the message that we intend to write
    std::string greeting = " Hello, " + name + "! ";

    // build the second and fourth lines of the output
    std::string spaces(greeting.size(), ' ');
    std::string second = "*" + spaces + "*";

    // build the first and fifth lines of the output
    std::string first(second.size(), '*');

    // write it all
    std::cout << first                   << std::endl
              << second                  << std::endl
              <<  "*" << greeting << "*" << std::endl
              << second                  << std::endl
              << first                   << std::endl;
}

Output :

Please enter your first name: Pejman
******************
*                *
* Hello, Pejman! *
*                *
******************

BY: Pejman Moghadam
TAG: cpp, cin, string
DATE: 2011-09-17 01:26:11


Pejman Moghadam / C-programming [ TXT ]