接受问候并写入输出

时间:2019-04-06 20:12:19

标签: c++ while-loop

我在阅读本书示例时编写的while循环正确地产生了第一行输出,但是循环结束了。您将如何“破坏”该程序?在其他语言中,我会用console.log()或类似的输出来填充我的代码,但是我不确定如何使用我刚开始学习C ++的C ++控制台项目来完成此任务。

#include <iostream>
#include <string>

int main()

{

    // ask for the name
    std::cout << "Please enter your first and last name: ";

    // read the name 
    std::string name; // define name
    std::string last;
    std::cin >> name; // read into name
    std::cin >> last;

    // build our message 
    const std::string greeting = "Hello, " + name + " " + last + "!";
    const int pad = 1;
    const int rows = pad * 2 + 3;
    const std::string::size_type cols = greeting.size() + pad * 2 + 2;
    std::string::size_type c = 0;


    // separate the output from the input by one line
    std::cout << std::endl;

    // write rows of output
    int r = 0;

我包括完整的程序,但下面是我认为问题所在的while循环。

    // invariant: we have written r rows so far 
    while (r != rows) {
        // write a row of output
        // invariant: we have written c characters so far 
        while (c != cols) {
            if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) {
                // this is the only line that gets written to the console 
                std::cout << "*";
                ++c;
            }
            else {
                // write non border characters
                //adjust the value of c to maintain the invariant
                if (r == pad + 1 && c == pad + 1) {
                    std::cout << greeting;
                    // account for the characters written to maintain the c invariant
                    c += greeting.size();
                }
                else {
                    std::cout << " ";
                    ++c;
                }
            }
        }

        std::cout << std::endl;
        ++r;
    }

    return 0;
}

我认为可能是std :: cout << std :: endl;在++ r之前。是否刷新其他任何输入?因此,我删除了它,发现程序写了完整的第一行,然后写了std :: endl,然后结束了执行。我还运行了while循环,我的逻辑似乎很合理,也许我错过了一些明显的东西?

总而言之,为什么我的程序在第一次迭代后就停止执行?

0 个答案:

没有答案