【发布时间】:2015-06-07 10:31:54
【问题描述】:
//Prints a box of X's with user unput of width and height. Uses a User-defined function
#include <iostream>
#include <cmath>
using namespace std;
void box(int height, int width, int h = 1, int w = 1);
int main() {
int width, height;
cout << "Please enter width (0-25): \n";
cin >> width;
while (!(cin >> width) || width < 0 || width > 25) {
cout << "Invalid entry. Please re-enter width: \n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Please enter height (0-25): \n";
cin >> height;
while (!(cin >> height) || height < 0 || height > 25) {
cout << "Invalid entry. Please re-enter height: \n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
void box(int height, int width, int h, int w)
{
for (int h = 1; h <= height; h++)
{
for (int w = 1; w <= width; w++)
cout << "X";
cout << endl;
}
}
我已经进行了建议的编辑,程序编译没有错误,但它不打印该框。我知道我需要在main中定义函数,但是当我写的时候:
框(宽、高);
它显示一个错误。另外,当我在命令提示符窗口中时,输出如下:
请输入宽度 (0-25): 12
12 请输入身高(0-25): 12
z 输入无效。请重新输入身高: 12 按任意键继续...
【问题讨论】:
-
不应该有分号:
...int w){...而不是...int w);{..。此外,我想知道,为什么你有 2 个额外的函数声明(一个在最顶部,另一个在定义上方)。只需将函数(仅一次)放在 main 上方即可。 -
在函数体开始之前有一个多余的分号。
-
您的输入循环有问题。
cin.clear()和cin.ignore用于流失败时(例如,他们输入字母)。但是,您永远不会测试流是否失败,因此在这种情况下,您会通过读取未初始化的变量来导致 UB。循环应该是while ( !(cin >> width) || width < 0 || width > 25 ),或者预先将width初始化为一个超出范围的值。 -
for (int h = 1; h <= int height; h++);应该是for (int h = 1; h <= height; h++)和w循环的相同更改 -
已编辑,但仍有问题
标签: c++ user-defined-functions