C++代写:CS162TheWizardSpellbookCatalog


练习C++基础语法,包括pointer, arrays, struct, I/O, Makefile 等。
![Sort](https://upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Shell_sorting_algorithm_color_bars.svg/220px-
Shell_sorting_algorithm_color_bars.svg.png)

Goals

  • Practice good software engineering design principles:
    • Design your solution before writing the program
    • Develop test cases before writing the program
  • Review pointers, arrays, command line arguments, and structs
  • Use file I/O to read from and write to files
  • Practice file separation and create Makefile
  • Use functions to modularize code to increase readability and reduce repeated code

Problem Statement

The great wizard school of Pogwarts has been adding a lot of new spellbooks to
their library lately. As a result of all the new literature some mischievous
students have been learning spells that are dangerous. In addition, it has
become increasingly difficult for the staff to find specific spells they want
to teach in class.
In order to alleviate these issues, the school administration has hired you to
create a spellbook catalog program that will allow for access restriction and
make searching for spellbooks easier.
To simplify your task, the school has provided you with their spellbook and
wizard profile information. These come in the form of two textfiles:
wizards.txt and spellbooks.txt. (NOTE: The two filenames are provided on the
command line and should not be hardcoded in your program!)
The spellbooks.txt file contains a list of Pogwarts’s spellbooks and their
included spells. This file will give you the spellbook and spell information
that your program will organize and display.
The wizards.txt file contains a listing of all wizards associated with
Pogwarts. This file will give your program the information needed to control
which spellbooks users can access.

Requirements

  1. Command Line Arguments
    When starting the program, the user will provide two command line arguments.
    The first command line argument will be the name of the file that holds the
    information about the wizards. The second command line argument will be the
    name of the file that contains the information about spellbooks and included
    spells. If the user does not provide two names of existing files, theprogram
    should print out an error message and quit. You can assume that the user
    always provides these two command line arguments in the correct order.
  2. Wizard Login
    Before the user can get information from the program, they must login. You
    must prompt the user for an ID and password. The ID of the must be all ints.
    If it isn’t, you must re-prompt the user for an ID that is only ints. You will
    then prompt the user for the password. The password will be a string that
    could contain any number of characters and numbers. You do not need to do any
    error handling on the password. You will then need to check this information
    against the wizard_info.txt file contents to determine which wizard is logging
    in. If there is no match, you must re-prompt for both username and password
    again. If the user fails to login after three attempts, you must provide an
    error message and quit out of the program. (Note: If the user provides an ID
    that is not all integers that should not count as an error towards the three
    attempts that they have to login). After a user logs in, you must display the
    corresponding name, ID, school position, and beard length.
  3. Sorting and Printing
    Once the user has logged in, they should be prompted with a list of different
    ways to display the sorted spellbook and spell information. Wizards with
    student status cannot view any spell that has an effect of death or poison and
    cannot view any spellbook with a spell that has an effect of death or poison.
    After the user has chosen an option, they should be asked if they want the
    information printed to the screen or written to a file. If they choose to
    write to a file, they should be prompted for a file name. If the file name
    already exists, the information should be appended to the file. If the file
    name does not exist, a file should be created, and the information should be
    written to the file. For your sorting, you CANNOT use the built-in sort
    function.
  4. Available Options (after successful login):
    * Sort spellbooks by number of pages: If the user picks this option, the books must be sorted in ascending order by number of pages. Books with a spell that have an effect of death or poison should not be displayed when a student is logged in (i.e. hide those books from the results when a student is logged in). Once they are sorted, you should print/write to file the title of the book and the number of pages it has.
    * Sort spells by effect: There are five types of spells: fire, bubble, memory_loss, death, poison. Remember that students cannot see spells that have the type death or poison. The spells with memory_loss as the effect should be listed first, followed by fire, bubble, poison, and death. Once they are sorted, you should print/write to file the spell name and its effect.
    * Sort by average success rate of spells: You must create a list of books sorted by the average success rate, in either ascending or descending order, of all the spells contained within the book. Once calculated, you should print/write to file the title of each applicable book and the corresponding average success rate. Books with a spell that have an effect of death or poison should not be displayed when a student is logged in (i.e. hide those books from the results when a student is logged in).
    * Quit: The program will exit.
  5. Run Again: Your program should continue sorting and printing/writing until the user chooses to quit.

Required Structs

The following structs are required in your program. They will help organize
the information that will be read in (or derived) from the files. You cannot
modify, add, or take away any part of the struct.

  1. The wizard struct will be used when you read in entries from the wizard.txt file. There are three options for position_title: “Headmaster”, “Teacher”, or “Student”.
    struct wizard {
    string name;
    int id;
    string password;
    string position_title;
    float beard_length;
    };
    —|—
  2. The spellbook struct will be used to hold information from the spellbooks.txt file. This struct holds information about a spellbook.
    struct spellbook {
    string title;
    string author;
    int num_pages;
    int edition;
    int num_spells;
    float avg_success_rate;
    struct spell *s;
    };
    —|—
  3. The spell struct will also be used to read in information from the spellbooks.txt file. This struct holds information about a spell. There are five options for effect: “fire”, “poison”, “bubbles”, “death”, or “memory_loss”.
    struct spell {
    string name;
    float success_rate;
    string effect;
    };
    —|—

Required Functions

You must implement the following functions in your program. You are not
allowed to modify these required function declarations in any way. Note: it is
acceptable if you choose to add additional functions (but you must still
include the required functions).

  1. This function will dynamically allocate an array of spellBooks (of the requested size):
    spellbook * create_spellbooks(int);
    —|—
  2. This function will fill a spellbook struct with information that is read in from spellbooks.txt. Hint: “ifstream &” is a reference to a filestream object. You will need to create one and pass it into this function to read from the spellbooks.txt file.
    void populate_spellbook_data(spellbook *, int, ifstream &);
    —|—
  3. This function will dynamically allocate an array of spells (of the requested size):
    spell * create_spells(int);
    —|—
  4. This function will fill a spell struct with information that is read in from spellbooks.txt.
    void populate_spell_data(spell *, int, ifstream &);
    —|—
  5. You need to implement a function that will delete all the memory that was dynamically allocated. You can choose the prototype. Possible options include the following: (Note the prototype of the parameters are wizard and spellbook , which refer to the addresses of the wizard and spellbook , not the 2D arrays)
    void delete_info(wizard **, int, spellbook **, int);
    void delete_info(wizard **, spellbook **, int);
    —|—

Required Input File Format

  1. Your program must accommodate the file formats as specified in this section. The wizards.txt file will have the following pattern: ---|--- An example wizards.txt file is provided here
  2. The spellbooks.txt file has a slightly different structure. The file information will be provided in sets (corresponding to each spellbook). Each spellbook will be accompanied by a listing of the spells inside.
    The spellbooks.txt file will have the following pattern: <author> <number of pages> <edition> <number of spells in book> <title of spell> <success rate> <effect> <title of spell> <success rate> <effect> <title of spell> <success rate> <effect> ... <title of second spellbook> <author> <number of pages> <edition> <number of spells in book> <title of spell> <success rate> <effect> <title of spell> <success rate> <effect> <title of spell> <success rate> <effect> <title of spell> <success rate> <effect> ... <title of third spellbook> <author> <number of pages> <edition> <number of spells in book> <title of spell> <success rate> <effect> <title of spell> <success rate> <effect> ... ---|--- An example spellbooks.txt file is provided here</li> </ol> <h3 id="README-txt-Description"><a href="#README-txt-Description" class="headerlink" title="README.txt Description"></a>README.txt Description</h3><p>A README is a text file that introduces and explains a project. Once you have<br>implemented and fully tested the Wizard Spellbook Catalog with all<br>functionalities described above, write a README.txt file that includes the<br>following information:</p> <ol> <li>Your name and ONID </li> <li>Description: One paragraph advertising what your program does (for a user who knows nothing about this assignment, does not know C++, and is not going to read your code). Highlight any special features. </li> <li>Instructions: Step-by-step instructions telling the user how to compile and run your program. Each menu choice should be described. If you expect a certain kind of input at specific steps, inform the user what the requirements are. Include examples to guide the user. </li> <li>Limitations: Describe any known limitations for things the user might want or try to do but that program does not do/handle.</li> </ol> <h3 id="Required-files"><a href="#Required-files" class="headerlink" title="Required files"></a>Required files</h3><p>You are expected to modularize your code into a header file (.h), an<br>implementation file (.cpp), and a driver file (.cpp).</p> <ol> <li>catalog.h: This header file contains all struct declarations and function prototypes </li> <li>catalog.cpp: This implementation file contains all function definitions </li> <li>run_wizard.cpp: This driver file contains the main function </li> <li>A Makefile is required </li> <li>A README.txt is required</li> </ol> <h3 id="Example-Operation"><a href="#Example-Operation" class="headerlink" title="Example Operation"></a>Example Operation</h3><p>The following snippet of text shows an example implementation of the spellbook<br>program. Note that this example does not illustrate all required behavior. You<br>must read this entire document to ensure that you meet all of the program<br>requirements. (User inputs are highlighted)<br>Note: This example output is only intended to illustrate the program<br>operation. Your values will be different.<br> $ ./catalog_prog wizards.txt spellbooks.txt<br> Please enter your id: 123456<br> Please enter your password: gr#ywiz<br> Incorrect id or password<br> Please enter your id: 123456<br> Please enter your password: gr3ywiz<br> Welcome Gandalf<br> ID: 123456<br> Status: Teacher<br> Beard Length: 9001<br> Which option would you like to choose?<br> 1. Sort spellbooks by number of pages<br> 2. Group spells by their effect<br> 3. Sort spellbooks by average success rate<br> 4. Quit<br> Your Choice: 1<br> How would you like the information displayed?<br> 1. Print to screen (Press 1)<br> 2. Print to file (Press 2)<br> Your Choice: 1<br> Spells_for_Dummies 303<br> Wacky_Witch_Handbook 1344<br> Necronomicon 1890<br> Forbidden_Tome 1938<br> Enchiridion 2090<br> The_Uses_of_Excalibur 3322<br> Charming_Charms 4460<br> Dorian 50000<br> Which option would you like to choose?<br> 1. Sort spellbooks by number of pages<br> 2. Group spells by their effect<br> 3. Sort spellbooks by average success rate<br> 4. Quit<br> Your Choice: 3<br> How would you like the information displayed?<br> 1. Print to screen (Press 1)<br> 2. Print to file (Press 2)<br> Your Choice: 1<br> Wacky_Witch_Handbook 90.05<br> The_Uses_of_Excalibur 87.9<br> Forbidden_Tome 76.8<br> Necronomicon 72.34<br> Enchiridion 51.2<br> Dorian 48.64<br> Charming_Charms 37.8<br> Spells_for_Dummies 29.74<br> Which option would you like to choose?<br> 1. Sort spellbooks by number of pages<br> 2. Group spells by their effect<br> 3. Sort spellbooks by average success rate<br> 4. Quit<br> Your Choice: 3<br> How would you like the information displayed?<br> 1. Print to screen (Press 1)<br> 2. Print to file (Press 2)<br> Your Choice: 2<br> Please provide desired filename: success_rate_list.txt<br> Appended requested information to file.<br> Which option would you like to choose?<br> 1. Sort spellbooks by number of pages<br> 2. Group spells by their effect<br> 3. Sort spellbooks by average success rate<br> 4. Quit<br> Your Choice: 2<br> How would you like the information displayed?<br> 1. Print to screen (Press 1)<br> 2. Print to file (Press 2)<br> Your Choice: 1<br> fire Blasto_Strike<br> fire Beginning_Blast<br> bubble Bubble_Beam<br> bubble Exploratory_Maneuver<br> memory_loss Space_Out<br> memory_loss Preliminary_Black_out<br> memory_loss Wacky_Dreams<br> poison Cthulhu_Venom<br> death Deathrock<br> death Nightmare<br> death Deadly_Details<br> Which option would you like to choose?<br> 1. Sort spellbooks by number of pages<br> 2. Group spells by their effect<br> 3. Sort spellbooks by average success rate<br> 4. Quit<br> Your Choice: 4<br> Bye! </p> <h2 id="Programming-Style-Comments"><a href="#Programming-Style-Comments" class="headerlink" title="Programming Style/Comments"></a>Programming Style/Comments</h2><p>In your implementation, make sure that you include a program header. Also<br>ensure that you use proper indentation/spacing and include comments! Below is<br>an example header to include. Make sure you review the style guidelines for<br>this class , and begin trying to follow them, i.e. don’t align everything on<br>the left or put everything on one line!<br> /******************************************************<br> ** Program: wizard_catalog.cpp<br> ** Author: Your Name<br> ** Date: 04/05/2020<br> ** Description:<br> ** Input:<br> ** Output:<br> ******************************************************/<br>—|—<br>Understanding the Problem/Problem Analysis:</p> <ul> <li>What are the user inputs, program outputs, etc.? </li> <li>What assumptions are you making? </li> <li>What are all the tasks and subtasks in this problem?<br>Program Design:</li> <li>What does the overall big picture of each function look like? (Flowchart or pseudocode) <ul> <li>What variables do you need to create, when you read input from the user? </li> <li>How to read from a file, and store information into your program? </li> <li>How to write information from your program to a file? </li> <li>What are the decisions that need to be made in this program? </li> <li>What tasks are repeated? </li> <li>How would you modularize the program, how many functions are you going to create, and what are they?</li> </ul> </li> <li>What kind of bad input are you going to handle?<br>Based on your answers above, list the specific steps or provide a flowchart of<br>what is needed to create. Be very explicit!!!</li> </ul> <h2 id="Program-Testing"><a href="#Program-Testing" class="headerlink" title="Program Testing"></a>Program Testing</h2><p>Create a test plan with the test cases (bad, good, and edge cases). What do<br>you hope to be the expected results?</p> <ul> <li>What are the good, bad, and edge cases for ALL input in the program? Make sure to provide enough of each and for all different inputs you get from the user.</li> </ul> <h2 id="Additional-Implementation-Requirements"><a href="#Additional-Implementation-Requirements" class="headerlink" title="Additional Implementation Requirements"></a>Additional Implementation Requirements</h2><ul> <li>Your user interface must provide clear instructions for the user and information about the data being presented </li> <li>Use of dynamic array is required. </li> <li>Use of command line arguments is required. </li> <li>Use of structs is required </li> <li>Your program must catch all required errors and recover from them. </li> <li>You are not allowed to use libraries that are not introduced in class. </li> <li>Your program should be properly decomposed into tasks and subtasks using functions.<br>To help you with this, use the following:<ul> <li>Make each function do one thing and one thing only. </li> <li>No more than 15 lines inside the curly braces of any function, including main().<br>Whitespace, variable declarations, single curly braces, vertical spacing,<br>comments, and function headers do not count.</li> <li>Functions over 15 lines need justification in comments.- </li> <li>Do not put multiple statements into one line.</li> </ul> </li> <li>No global variables allowed (those declared outside of many or any other function, global constants are allowed). </li> <li>No goto function allowed </li> <li>You must not have any memory leaks </li> <li>You program should not have any runtime error, e.g. segmentation fault </li> <li>Make sure you follow the style guidelines, have a program header and function headers with appropriate comments, and be consistent.</li> </ul> <h2 id="Compile-and-Submit-your-assignment"><a href="#Compile-and-Submit-your-assignment" class="headerlink" title="Compile and Submit your assignment"></a>Compile and Submit your assignment</h2><p>When you compile your code, it is acceptable to use C++11 functionality in<br>your program. In order to support this, change your Makefile to include the<br>proper flag.<br>For example, consider the following approach (note the inclusion of<br>-std=c++11):<br> g++ -std=c++11 <other flags and parameters><br>In order to submit your homework assignment, you must create a tarred archive<br>that contains your .h, .cpp, Makefile and README.txt files. This tar file will<br>be submitted to TEACH . In order to create the tar file, use the following<br>command:<br> tar -cvf assign1.tar catalog.h catalog.cpp run_wizard.cpp Makefile README.txt<br>Note that you are expected to modularize your code into a header file (.h), an<br>implementation file (.cpp), and a driver file (.cpp).<br>You do not need to submit the spellbooks.txt or wizards.txt. The TA’s will<br>have their own for grading</p> </div> <hr/> <div class="reprint" id="reprint-statement"> <div class="reprint__author"> <span class="reprint-meta" style="font-weight: bold;"> <i class="fas fa-user"> 文章作者: </i> </span> <span class="reprint-info"> <a href="/about" rel="external nofollow noreferrer">SafePoker</a> </span> </div> <div class="reprint__type"> <span class="reprint-meta" style="font-weight: bold;"> <i class="fas fa-link"> 文章链接: </i> </span> <span class="reprint-info"> <a href="https://bestcstutor.github.io/2022/06/25/C++%E4%BB%A3%E5%86%99%EF%BC%9ACS162TheWizardSpellbookCatalog/">https://bestcstutor.github.io/2022/06/25/C++%E4%BB%A3%E5%86%99%EF%BC%9ACS162TheWizardSpellbookCatalog/</a> </span> </div> <div class="reprint__notice"> <span class="reprint-meta" style="font-weight: bold;"> <i class="fas fa-copyright"> 版权声明: </i> </span> <span class="reprint-info"> 本博客所有文章除特別声明外,均采用 <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a> 许可协议。转载请注明来源 <a href="/about" target="_blank">SafePoker</a> ! </span> </div> </div> <script async defer> document.addEventListener("copy", function (e) { let toastHTML = '<span>复制成功,请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>'; M.toast({html: toastHTML}) }); function navToReprintStatement() { $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800); } </script> <div class="tag_share" style="display: block;"> <div class="post-meta__tag-list" style="display: inline-block;"> <div class="article-tag"> <a href="/tags/C-%E4%BB%A3%E5%86%99/"> <span class="chip bg-color">C++代写</span> </a> </div> </div> <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;"> <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css"> <div id="article-share"> </div> </div> </div> <div id="reward"> <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a> <!-- Modal Structure --> <div id="rewardModal" class="modal"> <div class="modal-content"> <a class="close modal-close"><i class="fas fa-times"></i></a> <h4 class="reward-title">你的赏识是我前进的动力</h4> <div class="reward-content"> <div class="reward-tabs"> <ul class="tabs row"> <li class="tab col s12 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li> </ul> <div id="wechat"> <img src="/medias/newqrcode.jpg" class="reward-img" alt="微信打赏二维码"> </div> </div> </div> </div> </div> </div> <script> $(function () { $('.tabs').tabs(); }); </script> </div> </div> <article id="prenext-posts" class="prev-next articles"> <div class="row article-row"> <div class="article col s12 m6" data-aos="fade-up"> <div class="article-badge left-badge text-color"> <i class="fas fa-chevron-left"></i> 上一篇</div> <div class="card"> <a href="/2022/06/26/C++%E4%BB%A3%E5%86%99%EF%BC%9ACMPT115HuffmanTreePart3/"> <div class="card-image"> <img src="/medias/featureimages/11.jpg" class="responsive-img" alt="C++代写:CMPT115HuffmanTreePart3"> <span class="card-title">C++代写:CMPT115HuffmanTreePart3</span> </div> </a> <div class="card-content article-content"> <div class="summary block-with-text"> </div> <div class="publish-info"> <span class="publish-date"> <i class="far fa-clock fa-fw icon-date"></i>2022-06-26 </span> <span class="publish-author"> <i class="fas fa-user fa-fw"></i> SafePoker </span> </div> </div> <div class="card-action article-tags"> <a href="/tags/C-%E4%BB%A3%E5%86%99/"> <span class="chip bg-color">C++代写</span> </a> </div> </div> </div> <div class="article col s12 m6" data-aos="fade-up"> <div class="article-badge right-badge text-color"> 下一篇 <i class="fas fa-chevron-right"></i> </div> <div class="card"> <a href="/2022/06/25/C++%E4%BB%A3%E5%86%99%EF%BC%9ACS2370ElecrtonicDevices/"> <div class="card-image"> <img src="/medias/featureimages/22.jpg" class="responsive-img" alt="C++代写:CS2370ElecrtonicDevices"> <span class="card-title">C++代写:CS2370ElecrtonicDevices</span> </div> </a> <div class="card-content article-content"> <div class="summary block-with-text"> </div> <div class="publish-info"> <span class="publish-date"> <i class="far fa-clock fa-fw icon-date"></i>2022-06-25 </span> <span class="publish-author"> <i class="fas fa-user fa-fw"></i> SafePoker </span> </div> </div> <div class="card-action article-tags"> <a href="/tags/C-%E4%BB%A3%E5%86%99/"> <span class="chip bg-color">C++代写</span> </a> </div> </div> </div> </div> </article> </div> <!-- 代码块功能依赖 --> <script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script> <!-- 代码语言 --> <script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script> <!-- 代码块复制 --> <script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script> <!-- 代码块收缩 --> <script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script> </div> <div id="toc-aside" class="expanded col l3 hide-on-med-and-down"> <div class="toc-widget card" style="background-color: white;"> <div class="toc-title"><i class="far fa-list-alt"></i>  目录</div> <div id="toc-content"></div> </div> </div> </div> <!-- TOC 悬浮按钮. --> <div id="floating-toc-btn" class="hide-on-med-and-down"> <a class="btn-floating btn-large bg-color"> <i class="fas fa-list-ul"></i> </a> </div> <script src="/libs/tocbot/tocbot.min.js"></script> <script> $(function () { tocbot.init({ tocSelector: '#toc-content', contentSelector: '#articleContent', headingsOffset: -($(window).height() * 0.4 - 45), collapseDepth: Number('0'), headingSelector: 'h2, h3, h4' }); // Set scroll toc fixed. let tocHeight = parseInt($(window).height() * 0.4 - 64); let $tocWidget = $('.toc-widget'); $(window).scroll(function () { let scroll = $(window).scrollTop(); /* add post toc fixed. */ if (scroll > tocHeight) { $tocWidget.addClass('toc-fixed'); } else { $tocWidget.removeClass('toc-fixed'); } }); /* 修复文章卡片 div 的宽度. */ let fixPostCardWidth = function (srcId, targetId) { let srcDiv = $('#' + srcId); if (srcDiv.length === 0) { return; } let w = srcDiv.width(); if (w >= 450) { w = w + 21; } else if (w >= 350 && w < 450) { w = w + 18; } else if (w >= 300 && w < 350) { w = w + 16; } else { w = w + 14; } $('#' + targetId).width(w); }; // 切换TOC目录展开收缩的相关操作. const expandedClass = 'expanded'; let $tocAside = $('#toc-aside'); let $mainContent = $('#main-content'); $('#floating-toc-btn .btn-floating').click(function () { if ($tocAside.hasClass(expandedClass)) { $tocAside.removeClass(expandedClass).hide(); $mainContent.removeClass('l9'); } else { $tocAside.addClass(expandedClass).show(); $mainContent.addClass('l9'); } fixPostCardWidth('artDetail', 'prenext-posts'); }); }); </script> </main> <footer class="page-footer bg-color"> <div class="container row center-align" style="margin-bottom: 0px !important;"> <div class="col s12 m8 l8 copy-right"> Copyright © <span id="year">2018-2024</span> <a href="/contact" target="_blank">SafePoker</a> <br> <span id="busuanzi_container_site_pv">  | <i class="far fa-eye"></i> 总访问量:  <span id="busuanzi_value_site_pv" class="white-color"></span> </span> <span id="busuanzi_container_site_uv">  | <i class="fas fa-users"></i> 总访问人数:  <span id="busuanzi_value_site_uv" class="white-color"></span> </span> <br> <!-- 运行天数提醒. --> <br> </div> <div class="col s12 m4 l4 social-link social-statis"> <a href="mailto:s4ferm4n@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50"> <i class="fas fa-envelope-open"></i> </a> </div> </div> </footer> <div class="progress-bar"></div> <!-- 搜索遮罩框 --> <div id="searchModal" class="modal"> <div class="modal-content"> <div class="search-header"> <span class="title"><i class="fas fa-search"></i>  搜索</span> <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字" class="search-input"> </div> <div id="searchResult"></div> </div> </div> <script type="text/javascript"> $(function () { var searchFunc = function (path, search_id, content_id) { 'use strict'; $.ajax({ url: path, dataType: "xml", success: function (xmlResponse) { // get the contents from search data var datas = $("entry", xmlResponse).map(function () { return { title: $("title", this).text(), content: $("content", this).text(), url: $("url", this).text() }; }).get(); var $input = document.getElementById(search_id); var $resultContent = document.getElementById(content_id); $input.addEventListener('input', function () { var str = '<ul class=\"search-result-list\">'; var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/); $resultContent.innerHTML = ""; if (this.value.trim().length <= 0) { return; } // perform local searching datas.forEach(function (data) { var isMatch = true; var data_title = data.title.trim().toLowerCase(); var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase(); var data_url = data.url; data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url; var index_title = -1; var index_content = -1; var first_occur = -1; // only match artiles with not empty titles and contents if (data_title !== '' && data_content !== '') { keywords.forEach(function (keyword, i) { index_title = data_title.indexOf(keyword); index_content = data_content.indexOf(keyword); if (index_title < 0 && index_content < 0) { isMatch = false; } else { if (index_content < 0) { index_content = 0; } if (i === 0) { first_occur = index_content; } } }); } // show search results if (isMatch) { str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>"; var content = data.content.trim().replace(/<[^>]+>/g, ""); if (first_occur >= 0) { // cut out 100 characters var start = first_occur - 20; var end = first_occur + 80; if (start < 0) { start = 0; } if (start === 0) { end = 100; } if (end > content.length) { end = content.length; } var match_content = content.substr(start, end); // highlight all keywords keywords.forEach(function (keyword) { var regS = new RegExp(keyword, "gi"); match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>"); }); str += "<p class=\"search-result\">" + match_content + "...</p>" } str += "</li>"; } }); str += "</ul>"; $resultContent.innerHTML = str; }); } }); }; searchFunc('/search.xml', 'searchInput', 'searchResult'); }); </script> <!-- 白天和黑夜主题 --> <div class="stars-con"> <div id="stars"></div> <div id="stars2"></div> <div id="stars3"></div> </div> <script> function switchNightMode() { $('<div class="Cuteen_DarkSky"><div class="Cuteen_DarkPlanet"></div></div>').appendTo($('body')), setTimeout(function () { $('body').hasClass('DarkMode') ? ($('body').removeClass('DarkMode'), localStorage.setItem('isDark', '0'), $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')) : ($('body').addClass('DarkMode'), localStorage.setItem('isDark', '1'), $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')), setTimeout(function () { $('.Cuteen_DarkSky').fadeOut(1e3, function () { $(this).remove() }) }, 2e3) }) } </script> <!-- 回到顶部按钮 --> <div id="backTop" class="top-scroll"> <a class="btn-floating btn-large waves-effect waves-light" href="#!"> <i class="fas fa-arrow-up"></i> </a> </div> <script src="/libs/materialize/materialize.min.js"></script> <script src="/libs/masonry/masonry.pkgd.min.js"></script> <script src="/libs/aos/aos.js"></script> <script src="/libs/scrollprogress/scrollProgress.min.js"></script> <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script> <script src="/js/matery.js"></script> <!-- 雪花特效 --> <!-- 鼠标星星特效 --> <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script> <script src="/libs/others/TencentCaptcha.js"></script> <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button> <!-- Baidu Analytics --> <!-- Baidu Push --> <script> (function () { var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })(); </script> <script src="/libs/others/clicklove.js" async="async"></script> <script async src="/libs/others/busuanzi.pure.mini.js"></script> <script src="/libs/instantpage/instantpage.js" type="module"></script> </body> </html>