1:
参考 http://blog.csdn.net/cstopcoder/article/details/21892867
第三种方法,
2:
输入时,用gets()读入含有空格的一样;
如果使用了scanf读入字符串后,需用一次getchar()吸收掉剩下的换行,再继续gets()下一行
scanf("%s",books[i].id); getchar(); //getchar()的作用是将第一行剩下的"\n"吸收掉 gets(books[i].title); //title中有空格,所以用gets
读入数字+字符串:
scanf("%d: ",&qnum); //固定格式qnum: qstr,正好方便用scanf读取后用gets读取剩下的内容 gets(qstr);
3:
本题只需要按ID排序:
qsort(books, n, sizeof(book), cmp); //只需要按ID排序,因为输出只要求按ID升序 //而且排序的只是前n个
4:
使用strstr()检查字符串中是否包含目标:
if(strstr(b.keyWords, qstr) != NULL){ //strstr(obj, target)返回一个char * 指针
5:
book books[10000+5];//数组开小了就会造成段错误
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; //参考http://blog.csdn.net/cstopcoder/article/details/21892867 typedef struct{ char id[10]; char title[81]; char author[81]; char keyWords[100]; char publisher[81]; char year[10]; }book; book books[10000+5];//数组开小了就会造成段错误 int cmp(const void * a, const void * b){ book b1 = *((book *)a); book b2 = *((book *)b); return strcmp(b1.id, b2.id); } void queryPrint(int qnum, char qstr[], int n){ int i; int found = 0; for(i = 0; i < n; i++){ book b = books[i]; switch(qnum){ case 1: if(strcmp(b.title, qstr) == 0){ printf("%s\n",b.id); found = 1; } break; case 2: if(strcmp(b.author, qstr) == 0){ printf("%s\n",b.id); found = 1; } break; case 3: if(strstr(b.keyWords, qstr) != NULL){ //strstr(obj, target)返回一个char * 指针 printf("%s\n",b.id); found = 1; } break; case 4: if(strcmp(b.publisher, qstr) == 0){ printf("%s\n",b.id); found = 1; } break; case 5: if(strcmp(b.year, qstr) == 0){ printf("%s\n",b.id); found = 1; } break; } } if(found ==0){ printf("Not Found\n"); } } int main(){ //freopen("in.txt","r",stdin); int n,m; scanf("%d", &n); int i; for(i = 0; i < n; i++){ scanf("%s",books[i].id); getchar(); //getchar()的作用是将第一行剩下的"\n"吸收掉 gets(books[i].title); //title中有空格,所以用gets gets(books[i].author); //有空格 gets(books[i].keyWords); //有空格 gets(books[i].publisher); //有空格 scanf("%s",books[i].year); } qsort(books, n, sizeof(book), cmp); //只需要按ID排序,因为输出只要求按ID升序 //而且排序的只是前n个 ////test //for(i = 0; i < n; i++){ // printf("id=%s\n",books[i].id); // printf("title=%s\n",books[i].title); // printf("author=%s\n",books[i].author); // printf("keyWords=%s\n",books[i].keyWords); // printf("publisher=%s\n",books[i].publisher); // printf("year=%s\n",books[i].year); //} scanf("%d", &m); while(m-- > 0){ int qnum; char qstr[100]; scanf("%d: ",&qnum); //固定格式qnum: qstr,正好方便用scanf读取后用gets读取剩下的内容 gets(qstr); printf("%d: %s\n", qnum,qstr); queryPrint(qnum, qstr, n); } return 0; }