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;
}