【问题标题】:C Primer Plus chapter 6 programming exercise 1C Primer Plus 第6章编程练习1
【发布时间】:2017-12-24 16:56:33
【问题描述】:

我使用从第 6 章(当前程序)中学到的知识解决了这个问题。我最初的想法是使用循环将值打印并扫描到数组中,然后打印数组的值,但我无法使其工作(主函数下的注释部分)。该程序只打印换行符(程序打印字母,但我必须按 Enter 键才能获取下一个字母)。主函数内程序中的注释部分是我想要做什么的想法。我在下面包含了该程序,并提前感谢您的帮助。

//This is a program to create an array of 26 elements, store
//26 lowercase letters starting with a, and to print them.
//C Primer Plus Chapter 6 programming exercise 1

#include <stdio.h>

#define SIZE 26

int main(void)
{
    char array[SIZE];
    char ch;
    int index;

    printf("Please enter letters a to z.\n");
    for(index = 0; index < SIZE; index++)
        scanf("%c", &array[index]);
    for(index = 0; index < SIZE; index++)
        printf("%c", array[index]);

    //for(ch = 'a', index = 0; ch < ('a' + SIZE); ch++, index++)
    //{ printf("%c", ch);
    //  scanf("%c", &array[index]);
    //}
    //for(index = 0; index < SIZE; index++)
    //  printf("%c", array[index]);

    return 0;
}

【问题讨论】:

  • 试试这个scanf("%c", &amp;array[index]); --> scanf(" %c", &amp;array[index]);
  • 当您输入字符然后按输入两个字符时。一个是您输入的字符,另一个是\n。这就是为什么你得到你所看到的。解决方案是消耗空白字符..这是通过将' ' 放入scanf 来完成的。
  • @coderredoc,输入“abcdef...”时也可以吗?
  • @coderredoc,对不起,我不是 scanf 专家。似乎用户信息很重要:"Please enter letters a to z. vs. "Please enter each letter a to z.
  • @PaulOgilvie.: 从标准 一个由空白字符组成的指令通过读取输入到第一个非空白字符(仍然未读取)来执行,或者直到无法读取更多字符。该指令永远不会失败。

标签: c


【解决方案1】:

这里的问题是

当您输入字符然后按enter 时,您输入了两个字符。一个是您输入的字母字符,另一个是\n。这就是为什么你得到你所看到的。解决方案是消耗空白字符..这是通过将' ' 放入scanf 来完成的。

scanf(" %c", &array[index]);
       ^

为什么有效?

引用standard- 7.21.6.2

由空白字符组成的指令由 读取输入直到第一个非空白字符(保留 未读),或直到无法读取更多字符。该指令从不 失败。

示例代码:

#include <stdio.h>
#include <stdlib.h>

#define SIZE 6

int main(void)
{
    char array[SIZE];
    int index;

    printf("Please enter letters a to z.\n");
    for(index = 0; index < SIZE; index++)
        if( scanf(" %c", &array[index]) != 1){
            fprintf(stderr,"%s\n","Error in input");
            exit(1);
        }
        else {
            printf("read: %c\n",array[index]);
        }
    for(index = 0; index < SIZE; index++)
        printf("%c", array[index]);

    putchar('\n');
    return 0;
}

【讨论】:

  • 我使用了 scanf("' '%c", &array[index]);我得到了以下结果:a(程序打印a,我按回车键)并且程序打印以下内容:bcdefghijklmnopqrstuvwxyz`�原����@p
  • scanf(" %c", &array[index]);只打印字母 a ,当我按 enter 时没有任何反应。我在 Fedora 27 中使用 gcc 以防万一很重要,并且在编译时也使用 --std=c11。
  • return:)之前添加putchar ('\n');,添加else printf ("read: %c\n", array[index]); 可能是有益的,并且可以使输出符合POSIX 标准
  • 我会找到确切的参考,但它基本上说所有进程都应输出最终的'\n'(所以它不会弄乱我的提示!)The Open Group Base Specifications Issue 7Shell & Utilities 注意: 我需要一天左右的时间才能在规范中找到准确的参考。我想今晚我的眼睛会发呆:)
  • @DavidC.Rankin.: 不用找了..我会去的。别担心。
猜你喜欢
  • 2018-06-06
  • 1970-01-01
  • 1970-01-01
  • 2014-07-20
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 1970-01-01
  • 2015-02-22
相关资源
最近更新 更多