c++ - 将用户输入的术语与 txt 文件中的列表进行比较
问题描述
我希望用户输入他们的姓名、性别、年龄、药物和状况。然后查看文本以查看他们的情况是否与文本文档中的任何其他人匹配,然后查看他们的年龄、性别或药物是否相同。如果它被输出,那么文本文档中可能存在的副作用。
自从我做这样的事情以来已经很久没有开始了。我只需要知道如何阅读和比较文本文档的基础知识。
Txt doc 的布局如下:
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()
。 - 对于每一行,搜索从文件中读取的字符串,搜索
searchString
用户输入的字符串userInput
,使用found = searchString.find(userInput, 0)
。您必须size_t found
在循环之前声明。 - 对于每一行,检查是否
userInput
在searchString
使用中找到if(found != std::string::npos)
- 如果找到打印 `searchString 到屏幕使用 'cout'
- 重复步骤 4-7 直到到达文件末尾
- 关闭文件
推荐阅读
- javascript - 在后端服务器端使用 Nodejs 进行动画渲染
- c - 将 IEEE-754 浮点编码转换为浮点值
- docker - Docker [emerg] 1#1:在单独的撰写文件后在上游找不到主机
- asp.net-mvc - 使用电子邮件或电话和密码验证登录
- javascript - 想要从 JSON 文件中获取数据。并以表格形式获取数据。但知道我想按字母顺序 AZ / ZA 甲酸盐搜索数据
- sql-server - 使用 where in 从不同的表中选择列
- css - 角度动态 css #
- c# - C#/.net/multithreading:在泛型集合上调用成员函数
- ios - iOS Swift:自定义交互过渡
- r - 当我尝试对它们进行分组时,为什么会得到一个额外的类别?