首页 > 解决方案 > 将用户输入的术语与 txt 文件中的列表进行比较

问题描述

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

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

Txt doc 的布局如下:

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

标签: c++searchtextgetline

解决方案


我不知道您需要多么“基本”,但是要读取和写入文件,您需要包含头文件“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. 对于每一行,搜索从文件中读取的字符串,搜索searchString用户输入的字符串userInput,使用found = searchString.find(userInput, 0)。您必须size_t found在循环之前声明。
  6. 对于每一行,检查是否userInputsearchString使用中找到if(found != std::string::npos)
  7. 如果找到打印 `searchString 到屏幕使用 'cout'
  8. 重复步骤 4-7 直到到达文件末尾
  9. 关闭文件

推荐阅读