fork download
  1. //ask for a person's name, and greet the person
  2. #include<iostream>
  3. #include<string>
  4.  
  5. using std::cin;
  6. using std::cout;
  7.  
  8. int main(){
  9. /*std::cout << "Please enter your name: ";
  10.   std::string name;
  11.   std::cin >> name;
  12.  
  13.   //build the message that we intend to write
  14.   const std::string greeting = "Hello, " + name + "!";
  15.  
  16.   //build the second and fourth lines of the output
  17.   const std::string spaces(greeting.size(), ' ');
  18.   const std::string second = "* " + spaces + " *";
  19.  
  20.   //build the first and fifth lines of the output
  21.   const std::string first(second.size(), '%');
  22.  
  23.   //write it all
  24.   std::cout << std::endl;
  25.   std::cout << first << std::endl;
  26.   std::cout << second << std::endl;
  27.   std::cout << "* "<< greeting<< " *"<< std::endl;
  28.   std::cout << second << std::endl;
  29.   std::cout << first << std::endl;
  30. {{
  31.   const std::string hello = "Hello";
  32.   const std::string message = hello + ",World" + "!"
  33. };} //why this compiles i have no idea
  34.   return 0; */
  35.  
  36. //ask for the person's name
  37. std::cout<< "please enter your first name: ";
  38.  
  39. //read the name
  40. std::string name;
  41. std::cin >> name;
  42.  
  43. //build the message that we intend to write
  44. const std::string greeting = "Hello. " + name + "!";
  45.  
  46. //the number of blanks surrounding the greeting
  47. const int pad = 1;
  48.  
  49. //the number of rows and columns to write
  50. const int rows = pad * 2 + 3;
  51. const std::string::size_type cols = greeting.size() + pad *2 + 2;
  52.  
  53. //write a blank line to separate the output from the input
  54. cout << std::endl;
  55.  
  56. //write rows rows of output
  57. //invariant: we have written r rows so far
  58. for (int r=0; r != rows ; ++r){
  59. std::string::size_type c = 0;
  60.  
  61. //invariant: we have written c characters so far in the current row
  62. while(c != cols){
  63.  
  64. //is it time to write the greeting?
  65. if(r == pad + 1 && c==pad +1){
  66. cout << greeting;
  67. c += greeting.size();
  68. }else {
  69.  
  70. //are we on the border?
  71. if (r == 0 || c ==0 || r == rows-1 || c == cols-1)
  72. cout << "*";
  73. else
  74. cout << " ";
  75. ++c;
  76. }
  77. }
  78.  
  79.  
  80.  
  81. return 0;
  82. }
  83. }
Success #stdin #stdout 0.01s 5312KB
stdin
karthy
stdout
please enter your first name: 
******************