[英]How to take two characters as input continuously?
I have to take input as: 我必须输入为:
A B
C D
E A
So I wrote the code like this : 所以我写了这样的代码:
char ch[50][2];
for(i=0;i<3;i++)
{
scanf("%c%c",&ch[i][0],&ch[i][1]);
}
But it is taking only two inputs and then, I am getting runtime error. 但是它仅接受两个输入,然后出现运行时错误。 Can anybody please help me?
有人可以帮我吗?
This is the method I often use: read the characters as strings. 这是我经常使用的方法:将字符读取为字符串。
for(i=0;i<3;i++)
{
char buf1[2], buf2[2];
scanf("%1s%1s",buf1,buf2);
ch[i][0]=buf1[0];
ch[i][1]=buf2[0];
}
Try 尝试
scanf(" %c %c",&ch[i][0],&ch[i][1]);
This would escape the newline \\n
character left in the buffer. 这样可以转义缓冲区中剩余的换行符
\\n
字符。
Try with a space between chars in scanf
尝试在
scanf
字符之间留一个空格
for(i=0;i<3;i++)
{
scanf(" %c %c", &ch[i][0], &ch[i][1]);
}
This will cause scanf
to ignore whitespace between characters. 这将导致
scanf
忽略字符之间的空格。 An extra space at the beginning is needed to also ignore new line character that the user inserts by pressing enter. 开头需要有一个额外的空格,以忽略用户通过按Enter键插入的换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.