c++ - 为什么我的代码对于形状 "rectangle"处于无限循环中?

标签 c++

这是代码

#include <iostream>
#include <string>
using namespace std;

void printTriangles(){
int length;
int width;
int base;
}


void printRectangles(){
int length;
int width;
int base;
string shape;
string repeat;
if ("rectangle" == shape)
{
    cout << "Enter the length of the rectangle: ";
    cin >> length;
    cout << endl;
    cout << "Enter the width of the rectangle: ";
    cin >> width;
}
if ("Rectangle" == shape)
{
    cout << "Enter the length of the rectangle: ";
    cin >> length;
    cout << endl;
    cout << "Enter the width of the rectangle: ";
    cin >> width;
}
for (int row = 1; row <= width; row++)
{
    for (int col = 1; col <= length; col++)
    {
        cout << "*";
    }
    cout << endl;
}

}
void printSquares(){
int length;
int width;
int base;
}


int main ()
{
int length;
int width;
int base;
string shape;
string repeat;

cout << "I will print squares for you!"<< endl << "Rectangles and triangles, too!"<< endl << endl;

cout << "Enter the shape that you would like to print (rectangle, triangle,  or square): ";
cin >> shape;

if ("rectangle" == shape)
printRectangles();
return 0;
}

当我输入 Rectangle 时,代码进入无限循环的星号,过去一天我一直在处理这个问题,但我还没有弄清楚我做错了什么。我相信我称我为“printRectangles();”功能正常,有人可以告诉我我是否正确调用了它。

最佳答案

在使用它们的值之前一定要初始化非静态局部变量。

试试这个:

void printRectangles(){
    int length = 0; // initialize for in case the reading fails
    int width = 0;

    // This is a function for printing rectangle,
    // so no checking for "rectangle", which is impossible because the input is not passed here

    cout << "Enter the length of the rectangle: ";
    cin >> length;
    cout << endl;
    cout << "Enter the width of the rectangle: ";
    cin >> width;
    for (int row = 1; row <= width; row++)
    {
        for (int col = 1; col <= length; col++)
        {
            cout << "*";
        }
        cout << endl;
    }

}

关于c++ - 为什么我的代码对于形状 "rectangle"处于无限循环中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35766371/

相关文章:

c++ - (C++) 得到错误:类::函数的无效使用,我一点也不知道为什么

c++ - 这在 C++ 中。它是如何工作的?

C++ Winsock编程,没有收到HTTP协议(protocol)的响应

c++ - 如何在模板类的 'namespace' 中创建非模板类型定义?

c++ - 从 C++ 输出流到 Android TextView 或等效的适配器?

c++ - 可以容纳任何东西的非模板容器

c++ - Linux 上的共享库版本和可执行文件

c++ - std::queue 位置的包装器

c++ - Boost 包含了严重破坏——但这不是 Boost 的错

c++ - 为什么 append Slot 不起作用?