C Primer Plus第6章编程练习1

问题描述 投票:0回答:1

我使用从第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;
}
c
1个回答
2
投票

这里的问题是

输入字符然后按Enter键时,输入两个字符。一个是你输入的字母字符,另一个是\n。这就是为什么你得到你所看到的。解决方案是消耗白色空间的charcaters ..这是通过将' '放在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;
}
© www.soinside.com 2019 - 2024. All rights reserved.