[英]i cant get this program to work correctly.
I have been asked to modify a program to read characters rather than numbers. 我被要求修改程序以读取字符而不是数字。 i modified the array into a char array. 我将数组修改为char数组。 changed the two "%d" to "%c" as below 如下将两个“%d”更改为“%c”
void main (void) { void main(void){
char a[100];
int counter;
int b;
counter = 0;
printf("please enter the length of the array: ");
scanf("%d", &b );
while (counter != b)
{
printf("please enter character: ");
scanf("%c", &a[counter]);
counter++;
}
a[counter] = '\0' ;
counter = 0;
while (a[counter] != '\0')
{
printf("\n");
printf("%c",a[counter]);
counter++;
}
}
please enter the length of the array: (4) 请输入数组的长度:(4)
please enter character: please enter character: (a) 请输入字符:请输入字符:(a)
please enter character: please enter character: (a) 请输入字符:请输入字符:(a)
a 一种
a 一种
() are used to indicate the user inputs. ()用于指示用户输入。
would be really good if i could get some help. 如果我能得到一些帮助,那将是非常好的。
You have to remember that scanf
leaves the newline in the input buffer, so when you try to read a character it will that newline. 您必须记住, scanf
将换行符留在输入缓冲区中,因此当您尝试读取字符时,它将换行。
The solution is very simple: Tell scanf
to read and discard leading whitespace, by adding a space in the format code: 解决方案非常简单:通过在格式代码中添加空格,告诉scanf
读取和丢弃前导空白:
scanf(" %c", &a[counter]);
/* ^ */
/* | */
/* Note space here */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.