将用户输入的术语与 txt 文件中的列表进行比较
Comparing terms entered by the user to lists in a txt file
我希望用户输入他们的姓名、性别、年龄、药物和状况。 然后浏览文本,看看他们的病情是否与文本文档中的任何其他人相匹配,然后看看他们的年龄、性别或药物是否相同。 如果它已出来,则在文本文档中也可能存在副作用。
自从我做这样的事情以来已经很久了,所以很难开始。我只需要知道如何阅读和比较文本文档的基础知识。
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
}
专门针对您的问题:
- 向用户请求其中一列(无需请求所有列。名称、状况或症状效果最好)。
- 打开数据文件
- 使用
getline(inFile, junk, 'n');
跳过第一行(您不想搜索列标题)。junk
是一个字符串变量,inFile
是你的".txt"文件。 - 再次使用
getline()
读取文件中的下一行。 - 对于每一行,使用
found = searchString.find(userInput, 0)
搜索从文件中读取的字符串,searchString
userInput
中搜索用户输入的字符串。您必须在循环之前声明size_t found
。 - 对于每一行,使用
if(found != std::string::npos)
检查是否在searchString
中找到userInput
- 如果找到,请使用"cout"将"搜索字符串"打印到屏幕上
- 重复步骤 4-7,直到到达文件末尾
- 关闭文件
相关文章:
- 读取文件的最后一行并输入到链接列表时出错
- 如何从远程 SFTP 服务器获取 HH-MM-SS 时间戳格式的文件列表
- 给定一个源文件,有没有办法要求 gcc 返回仅直接包含的头文件的列表?
- 是否可以将图像列表保存到文件中?
- 如何在 Windows 上获取带有 c++ 且没有 <dirent.h> 的特定扩展名的所有文件的列表
- 使用通配符的跨平台文件列表
- 对"列表"的引用不明确,包括头文件
- 从文本文件读取并保存到列表
- 从文本文件读取,然后将项目存储到列表中
- 是否可以使用 std::文件系统获取根名称列表?
- 从 .so/.o 文件中获取 C/cpp 中的静态库列表
- 如何将地图<列表<string>、矢量<string>>输出到输出文件?
- 如何显示目录中的文件列表
- 如何读取文件的内容,如果文件中的单词重复,请将它们添加到列表中?
- 使用命令列表解析自定义文件
- 如何通过在逗号处拆分将文件读入 2D 列表
- 正确的生成文件依赖项列表 (C++)
- 从一个cpp中给出所使用的头文件和hpp文件的列表
- C++中的递归列表文件不会进入所有子目录
- 在Visual Studio 2013中使用/fa制作列表文件