Scanf 漏线 [英] Scanf missed line
问题描述
我编写了一个测试程序,它应该接收一个 3x3 的字符矩阵并输出输入的矩阵.但是,我必须输入 4 行才能让程序生成相应的矩阵.我查了 scanf 函数的问题,但我尝试过的解决方案似乎都不起作用……你能帮我解决这个问题吗?
I wrote a test program which should take in a 3x3 matrix of characters and output the entered matrix. However, I have to enter 4 lines in order for the program to produce the corresponding matrix. I have looked up problems on the scanf function, but none of the solutions I tried seemed to work...Could you help me out with this?
我的代码:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char a[3][3];
int i,j;
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
scanf("%c",&a[i][j]);
}
scanf("\n");
}
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
printf("%c",a[i][j]);
}
printf("\n");
}
system("PAUSE");
return(0); }
推荐答案
已经尝试过您的并且它有效.虽然,我确实对每个评论做了一些更改:
Have tried your and IT WORKED. Although, I did make a few changes per comments:
#include <stdio.h> // added, but that shouldn't matter
main()
{
char a[3][3];
int i,j;
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
scanf("%c",&a[i][j]);
}
//scanf("\n"); // not necessary, see below
}
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
printf(" %c",a[i][j]);
}
printf("\n");
}
return(0);
}
在 Eclipse/Microsoft C Compiler 上编译并运行此代码并输入一系列字符,然后按 Enter.
Compiled and ran this code on Eclipse/Microsoft C Compiler and entered series of characters followed by enter.
abcdefghi
a b c
d e f
g h i
混淆点可能是 scanf
从控制台缓冲区中提取数据.通常,(尽管您可以解决此问题)当您按 Enter 时,该缓冲区会返回到您的程序.此外,%c
的格式说明符也接受空格.因此,我尝试使用以下输入和输出进行第二次运行.
The point of confusion might be that scanf
pulls the data from a console buffer. Typically, (although you can work around this) that buffer is returned to your program when you press enter. Also, the format specifier of %c
also accepts blanks. Thus, I tried a second run with the following input and output.
a b c d e
a b
c
d e
您可以分辨出空格和字母已被读取和存储.
You can tell the spaces were read and stored as well as the letters.
希望这会有所帮助.
这篇关于Scanf 漏线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!