1.1 Input
1 // ask for a person‘s name, and greet the person 2 #include <iostream> 3 #include <string> 4 5 int main() 6 { 7 // ask for a person‘s name 8 std::cout << "Please enter your name : " ; 9 10 // read the name 11 std::string name; // define name 12 std::cin >> name; // read into 13 14 // write a greeting 15 std::cout << "Hello, "<< name << " ! " << std::endl; 16 return 0; 17 } 18 19 /* 20 在VC6.0中的运行的结果是: 21 -------------------------------- 22 Please enter your name : Andrew 23 Hello, Andrew ! 24 -------------------------------- 25 */
1.2 Framing a name
1 // ask for a person‘s name, and generate a framed greeting 2 #include <iostream> 3 #include <string> 4 5 int main() 6 { 7 std::cout << "Please enter your name : " ; 8 std::string name; 9 std::cin >> name; 10 11 // build the message that we intend to write 12 const std::string greeting = "Hello , " + name + "!" ; 13 14 // build the second and fourth lines of the output 15 const std::string spaces(greeting.size(), ‘ ‘); 16 const std::string second = "*" + spaces + "*"; 17 18 // build the first and fifth lines of the output 19 const std::string first(second.size(), ‘*‘); 20 21 // write it all 22 std::cout << std::endl; 23 std::cout << first << std::endl; 24 std::cout << second << std::endl; 25 std::cout << "*" << greeting << "*" << std::endl; 26 std::cout << second << std::endl; 27 std::cout << first << std::endl; 28 return 0; 29 } 30 31 /* 32 在VC6.0中的运行的结果是: 33 -------------------------------- 34 Please enter your name : X_man 35 36 **************** 37 * * 38 *Hello , X_man!* 39 * * 40 **************** 41 -------------------------------- 42 */
时间: 2024-10-12 20:42:58