c++课堂练习,为姓名装框,打印名片类似问题。
一下我分享两种方法:
第一种:一行一行的打印。
#include <iostream>
#include<string>
int main()
{
using namespace std;
cout << "please inter your name:"<<endl;
string name;
cin >> name;
const string greeting = "hello," + name + "!";
const string spaces(greeting.size(),' ');
const string second = "*" + spaces + "*";
const string first(second.size(), '*');
cout << endl;
//一行一行打印
cout << first << endl;
cout << second << endl;
cout << "*" << greeting << "*" << endl;
cout << second << endl;
cout << first << endl;
return 0;
}
第二种:
分模块打印,分别为打印“*”号方框,打印空格,打印“hello,姓名!”
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "please inter your name :" << endl;
string name;
cin >> name;
const string greeting = "hello," + name + "!";
const int pad = 1;
const int rows = pad * 2 + 3;//行数
const string::size_type cols = greeting.size() + pad * 2 + 2;//列数
cout << endl;
for (int r = 0; r != rows; r++)
{
string::size_type c = 0;
while (c != cols)
{
if (r == pad + 1 && c == pad + 1)
{
cout << greeting+" ";
c += greeting.size();
}
else
{
if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1)
{
cout << "*";
}
else
{
cout << " ";
}
}
c++;
}
cout << endl;
}
return 0;
}