【问题标题】:Printing and scanning in CC中的打印和扫描
【发布时间】:2013-01-09 19:22:15
【问题描述】:

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

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 函数来读取用户输入,但我不知道该怎么做。

【问题讨论】:

  • writePattern(...)功能还没实现?你想实现它吗?
  • 我没有展示所有的代码……但它已经实现了。这只是我需要用来询问用户他们希望评论框有多高和多宽的代码的一部分,然后当我运行编译器时,它将绘制指定大小的框。
  • 不要编辑标题和问题以完成虚无,要么接受答案,要么将其保持打开状态,以便其他人可以搜索和寻求帮助。

标签: c loops printf scanf


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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
    

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

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

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

    【讨论】:

    • 检查scanf()调用的返回值怎么样? ;)
    【解决方案3】:

    请试试这个代码:

    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?
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      相关资源
      最近更新 更多