gpt4 book ai didi

scanf 漏行

转载 作者:行者123 更新时间:2023-12-04 20:48:52 25 4
gpt4 key购买 nike

我编写了一个测试程序,它应该接收一个 3x3 字符矩阵并输出输入的矩阵。但是,我必须输入 4 行才能让程序生成相应的矩阵。我查找了有关 scanf 函数的问题,但我尝试过的所有解决方案似乎都不起作用...您能帮我解决这个问题吗?

我的代码:

#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") 替换为 cin.get()

关于scanf 漏行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com