C 入门加版第 6 章编程练习 1.

  • 本文关键字:编程 练习 c
  • 更新时间 :
  • 英文 :


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

//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;
}

这里的问题是

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

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

为什么有效?

引用标准-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,"%sn","Error in input");
exit(1);
}
else {
printf("read: %cn",array[index]);
}
for(index = 0; index < SIZE; index++)
printf("%c", array[index]);
putchar('n');
return 0;
}

最新更新