-3

我需要询问用户要绘制一个评论框的高度和宽度,然后当我运行编译器时,它会绘制一个适当大小的框。这是我正在使用的代码:

int main() {
    int i;

    writePattern('/', '*', '/', ' ', ' ',1, LENGTH-2,1,0,0, LENGTH); //top of box being created

    for(i=1; i<=5; i++)
        writePattern('/', '*', ' ', '*', '/', 1,1, LENGTH-4, 1,1, LENGTH); //sides of box

    writePattern('/', '*', '/', ' ', ' ', 1 , LENGTH-2,1,0,0,LENGTH); //bottom of box

    return 0;
}

那么我该怎么做呢?我是 C 新手,所以我需要一些帮助。我知道我将不得不使用 printf 和 scanf 函数来读取用户输入,但我不知道该怎么做。

4

3 回答 3

0

请尝试以下代码:

printf("Enter the width: ");
int width;
if (scanf("%d", &width) != 1) {
    printf("Invalid number!");
    return 1; // Just return nothing or some error code?
}

printf("Enter the height: ");
int height;
if (scanf("%d", &height) != 1) {
    printf("Invalid number!");
    return 1; // Just return nothing or some error code?
}
于 2013-01-25T18:56:41.923 回答
0

在继续之前......学习如此美丽的语言是一个非常明智的想法!但是,当您开始时,请确保您从一开始就做正确的事情。

我建议您不要使用该scanf()功能。如果用户没有输入请求的东西,它会导致你的程序失败。你宁愿调用一般的流函数,例如fgets()然后解析你得到的字符串。看看另一个这样的问题:scanf() 和 fgets() 之间的区别
你可能会在那里得到有用的提示。

于 2013-01-25T20:50:08.990 回答
0

您只需要打印和扫描方面的帮助吗?

int x, y;
printf("How wide do you want your box?");
if (!scanf("%d", &x))
    //printf that they did it incorrectly and try again, probably in a while loop
printf("how wide?");
if (!scanf("%d", &y))
    //printf that they did it incorrectly and try again, probably in a while loop

where%d将获取或打印一个数字、%s一个字符串、%f一个分数等,您可以查找其他任何内容。

编辑:哎呀我忘了 & 来引用变量的地址

EDIT2:添加了建议的错误处理

于 2013-01-25T18:54:08.297 回答