题本身很水,但逗比的过程中发现了:
1: 不要用strcmp比较两个数字型字符串的大小:
printf("%d\n",strcmp("60","100"));//return 1即 60 > 100,因为strcmp 比较首字符发现不等就返回了!
2 : 将int转成一个char数组又忘了:
char buf[30];
sprintf(buf, "%d", stus[i].g) ;//将int转为char数组存入buf中
3:头文件没包含<string>但是写了namespace时,
vector<string> res;//没包含<string>, 加上namespace后这里不会报错找不到string,
//但是在cout<<res[i]时会报错“没有这些操作数匹配的<<运算符”
#include <iostream>
#include <string>
#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
int n;
int g1, g2;
typedef struct stu{
char name[12];
char id[12];
int g;
};
stu stus[10000];
int cmp(const void * a, const void * b){
stu sa = *(stu *)a;
stu sb = *(stu *)b;
return (sb.g-sa.g);
}
int main(){
freopen("in.txt","r",stdin);
scanf("%d", &n);
for(int i = 0; i < n; i++){
stu s;
scanf("%s %s %d", &s.name, &s.id, &s.g);
stus[i] = s;
}
scanf("%d%d",&g1, &g2);
qsort(stus, n, sizeof(stu), cmp);
//test
/*for(int i = 0; i < n;i++){
printf("%s %s %d \n", stus[i].name, stus[i].id, stus[i].g);
}*/
vector<string> res;//没包含<string>, 加上namespace后这里不会报错找不到string,
//但是在cout<<res[i]时会报错“没有这些操作数匹配的<<运算符”
for(int i = 0; i < n; i++){
if(stus[i].g >= g1 && stus[i].g <= g2 ) {
char buf[30];
string tmp = "";
tmp += stus[i].name;
tmp += " ";
tmp += stus[i].id;
//tmp += " ";
//sprintf(buf, "%d", stus[i].g) ;//将int转为char数组存入buf中
//tmp += buf;
res.push_back(tmp);
}
}
if(!res.empty()){
//for(vector<string>::iterator it = res.begin(); it != res.end(); it++){
for(int i = 0; i < res.size(); i++){
cout<<res[i]<<endl;
}
}else{
printf("NONE");
}
return 0;
}