我编写了一个测试程序,它应该接受 3x3 字符矩阵并输出输入的矩阵。但是,我必须输入 4 行才能让程序生成相应的矩阵。我已经查找了 scanf 函数的问题,但我尝试过的解决方案似乎都不起作用......你能帮我解决这个问题吗?
My code:
#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); }
scanf("%c",...)
获取空格和\n
。您可以通过多种方式解决:
如果你读像a b c
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
scanf("%c",&a[i][j]);
cin.get(); //Get the spaces after each character and the \n at the end of each line
}
}
或者你可以简单地使用cin
(使用 scanf 读取字符/字符串输入始终是一个问题)
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
cin >> a[i][j];
}
}
如果你正在阅读abc
,你只需要替换你的scanf("\n")
for a cin.get()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)