Points to note when scanf reads character arrays

Cause: The %c format of scanf can read spaces and carriage returns

 

When reading a two-dimensional character array separated by no spaces

#include<bits/stdc++.h>
using namespace std;
char mp[10][10]; 
signed main()
{
	for(int i=1;i<=3;i++){
		for(int j=1;j<=3;j++){
			scanf("%c",&mp[i][j]);
		}
		getchar();//吸收回车,不然会被scanf读取 
	}
    puts("");
	for(int i=1;i<=3;i++){
		for(int j=1;j<=3;j++){
			printf("%c ",mp[i][j]);
		}
		puts("");//换行 
	}
	return 0; 
}

 input and output

 

When reading a two-dimensional character array separated by spaces

#include<bits/stdc++.h>
using namespace std;
char mp[10][10]; 
signed main()
{
	for(int i=1;i<=3;i++){
		int j; 
		for(j=1;j<=2;j++){
			scanf("%c ",&mp[i][j]);//%c后记得接空格
		}
		scanf("%c",&mp[i][j]);
		getchar();//吸收回车,不然会被scanf读取 
	}
    puts("");
	for(int i=1;i<=3;i++){
		for(int j=1;j<=3;j++){
			printf("%c ",mp[i][j]);
		}
		puts("");//换行 
	}
	return 0; 
}

input and output 

 

Guess you like

Origin blog.csdn.net/weixin_61725823/article/details/130913544