将用户输入的术语与 txt 文件中的列表进行比较

Comparing terms entered by the user to lists in a txt file

本文关键字:列表 文件 比较 txt 用户 输入 术语      更新时间:2023-10-16

我希望用户输入他们的姓名、性别、年龄、药物和状况。 然后浏览文本,看看他们的病情是否与文本文档中的任何其他人相匹配,然后看看他们的年龄、性别或药物是否相同。 如果它已出来,则在文本文档中也可能存在副作用。

自从我做这样的事情以来已经很久了,所以很难开始。我只需要知道如何阅读和比较文本文档的基础知识。

Txt 文档的布局如下:

Name Med Sex Age Cond Effect
Bill DepMed M 33 Depression StomachAche 
Tom ADDMed  M 24 ADD HeadAche

我不知道你需要多"基本",但要读取和写入文件,你需要包含头文件"fstream"。您可以通过多种方式读取和写入文件。一种方法是打开文件,而不是使用cin进行输入和cout进行输出,而是使用打开文件的文件流的名称。例:

#include <fstream>
int main() {
string input;
fstream dataFile; //names stream 'dataFile' sort of like a variable.
dataFile.open("data.txt", ios::in | ios::out); //opens data.txt for reading (ios::in) and writing (ios::out)
dataFile >> input; //stores data to input exactly like 'cin' would from the screen, but in this case the input is coming from 'dataFile'
getline(dataFile, input, 'n'); //stores data to input exactly like 'cin.getline()' would
dataFile << "String to be added in file" << endl; //prints to file exactly like 'cout' prints to screen
dataFile.close() //closes file, be sure to do this or else you risk memory leak issues
}

专门针对您的问题:

  1. 向用户请求其中一列(无需请求所有列。名称、状况或症状效果最好)。
  2. 打开数据文件
  3. 使用getline(inFile, junk, 'n');跳过第一行(您不想搜索列标题)。junk是一个字符串变量,inFile是你的".txt"文件。
  4. 再次使用getline()读取文件中的下一行。
  5. 对于每一行,使用found = searchString.find(userInput, 0)搜索从文件中读取的字符串,searchStringuserInput中搜索用户输入的字符串。您必须在循环之前声明size_t found
  6. 对于每一行,使用if(found != std::string::npos)检查是否在searchString中找到userInput
  7. 如果找到,请使用"cout"将"搜索字符串"打印到屏幕上
  8. 重复步骤 4-7,直到到达文件末尾
  9. 关闭文件