好的,我是编程新手,因此决定阅读这本名为 Accelerated C++ 的书。我只在第二章,我尝试按照练习进行操作,即创建一个询问您的姓名的程序,然后输出它并在其周围加上一个框架和填充。
当我执行它时,它似乎没有移动到下一行。我猜这与我的 while() 循环有关,但我太笨了,无法弄清楚它到底是什么
// ask for a person's name, and greet the person
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::string;
int main()
{
// fetch name
cout << "Please enter your first name: ";
string name;
cin >> name;
// message
const string greeting = "Hello, " + name + "!";
// padding
const int pad = 1;
//desired rows/columns
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;
// seperate output from input
cout << std::endl;
// invariants
int r = 0;
string::size_type c = 0;
while (r != rows) {
while(c != cols) {
if (r == 0 || r == rows -1 || c == 0 || c == cols -1) { // if in bordering column or row
cout << "*"; //output *
} else {
if (r == pad + 1 && c == pad + 1) { //if on row for greeting
cout << greeting; // write greeting
c += greeting.size(); // adjust invariant
} else {
cout << " ";
}
}
++c;
}
++r;
cout << std::endl;
}
return 0;
}