c++ - While() 循环在文本周围创建星号边框?

标签 c++

好吧,我是编程新手,决定学习这本名为 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;
}

最佳答案

考虑将列计数器 c 移动到更靠近您使用它的位置,然后正如 tuckermi 所说,它将从每一行的 0 开始。

while (r != rows) {
    string::size_type c = 0;
    while(c != cols) {

关于c++ - While() 循环在文本周围创建星号边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17988493/

相关文章:

c++ - 为什么 defined(X) 在没有空格的预处理器定义中不起作用?

c++ - 如何逐步更新QMainWindow?

c++ - opencv 项目中的 CMakeLists.txt 出错

c++ - std::bind() 中 static_cast 的仿函数版本

c++ - 最有效的 const char* 比较不区分大小写

c++ - 程序说词典不存在

c++ - 无法理解算法以找到子数组的最大和

c++ - 如何从 'const tm*' 生成 'const tm&' ?

c++ - 有一种方法可以区分标题类型吗?

c++ - libwayland 的功能已弃用——替代方案?