C语言I/O小结 poj百练2804字典(基础题)

来源:互联网 发布:sql培训班 编辑:程序博客网 时间:2024/06/11 21:14

这个题目字典的输入是一个问题

遇到空行结束

那么如何使用好scanf 和 gets呢,数据量大肯定还是要用C的I/O的

 

sscanf是一个很不错的函数

刚好解决了这个问题

我们知道scanf会把换行符留在缓冲区中,而gets()读取的是一行

sscanf对于字典读入作用很好

 

基本算法:   排序 +  二分

数据量大,参考的网上别人写的

#include <fstream>#include <string.h>#include <stdio.h>#include <algorithm>#define _cdebbugusing std::sort;//全局数据char temp1[200];#define MAX_WORD_LEN 11#define MAX_DICTION_ITEM (100000 + 10)struct Dictionary{    char szWord[MAX_WORD_LEN];    char szEnglish[MAX_WORD_LEN];};Dictionary diction[MAX_DICTION_ITEM];bool CmpDictionItem(Dictionary one, Dictionary two){    return strcmp(one.szWord, two.szWord) < 0;}int FindEnglish(char* pszWord, int nItemNum){    int nBeg = 0, nEnd = nItemNum - 1;    int nCmp = 0;        while (nBeg <= nEnd)    {        int nMid = (nBeg + nEnd) / 2;        nCmp = strcmp(pszWord, diction[nMid].szWord);        if (nCmp == 0)        {            return nMid;        }        else if (nCmp < 0)        {            nEnd = nMid - 1;        }        else        {            nBeg = nMid + 1;        }    }        return -1;}int main(){//重定向#ifdef _cdebbugfreopen("F:\\input.txt","r",stdin );#endifint i,j;i = 0;int nCount = 0;int nAnsItem = 0;//读入字典char temp[30];while(gets(temp)  ){if(!strcmp(temp,""))break;sscanf(temp, "%s%s", diction[nCount].szEnglish, diction[nCount].szWord);        ++nCount;}//sortsort(diction, diction + nCount, CmpDictionItem);//查找char szWord[MAX_WORD_LEN];while (scanf("%s", szWord) == 1)    {        if ((nAnsItem = FindEnglish(szWord, nCount)) != -1)        {            printf("%s\n", diction[nAnsItem].szEnglish);        }        else        {            printf("eh\n");         }    }//printf("\n");//解除重定向关闭文件#ifdef _cdebbugfclose(stdin); #endifreturn 0 ;}