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