pat:1018 scanf读取字符;段错误

scanf 读取字符问题:

输入格式:

10
C J
J B
C B
B B
B C
C C
C B
J B
B C
J J
翻译为输入流为:

10\nC J\nJ B\n........


while(scanf("%d", &n));

scanf("%c %c", &a, &b);

读入10后,指针指向了\n,在使用%c时,是不会跳过空格,制表符,换行符的。所以读取的结果是a = '\n';这就与本意不对了。

scanf叫格式化输入,那么我们应该使用下面的:

while(scanf("%d\n", &n){//读取数字后跳过换行
              scanf("%c %c\n", &a, &b);//格式为读取一个字符,跳过一个空格读取一个字符,再跳过一个换行符
              //......
}


段错误问题:

原因:

1.访问越界;

2.数组太小;

#include <stdio.h>
#include <cctype>
#include <cmath>
#include <cstring>

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <stack>

#define SIZE 50000      //题目说数据量不超过10^5,所以设置为10^5/2

//#define SIZE 2		//段错误
//#define SIZE 10000	//段错误
//#define SIZE 100000	//段错误

using namespace std;

int Judge(string s1, string s2){
	if( (s1=="C" && s2=="J") || (s1=="J" && s2=="B") || (s1=="B" && s2=="C") )
		return 1;
	else if(s1 == s2)
		return 0;
	else 
		return -1;
}

void Best(string buf[], int n){
	sort(buf, buf+n);
	int i;
	int cc=0, cb=0, cj=0;
	for(i=0; i<n; i++){
		if(buf[i] == "B")
			cb++;
		else if(buf[i] == "C")
			cc++;
		else
			cj++;
	}
	int max = cc > cb ? cc:cb;
	char maxc = cc > cb ? 'C':'B';
	maxc = cj > max ? 'J':maxc;
	printf("%c", maxc);
}

int main(){
#ifdef ONLINE_JUDGE
#else	
	freopen("E:\\in.txt", "r" , stdin);
#endif

	int n;
	while(scanf("%d", &n) != EOF){
		string s1, s2;//
		string b1[SIZE], b2[SIZE];
		int cn1=0, cn2=0, cn3=0;// 甲,乙, 平

		while(n-->0){
			cin >> s1 >> s2;
			if(Judge(s1, s2)> 0)				
				b1[cn1++]=s1;
			else if(Judge(s1, s2) < 0)
				b2[cn2++]=s2;
			else
				cn3++;
		}//read

		printf("%d %d %d\n", cn1, cn3, cn2);
		printf("%d %d %d\n", cn2, cn3, cn1);

		Best(b1, cn1);
		printf(" ");

		// 乙
		Best(b2, cn2);
		printf("\n");
	}//while
	return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值