从.txt文件找到并验证C 的特定用户ID

Locating and validating a specific user ID from .txt file for c++

本文关键字:用户 ID 验证 文件 txt      更新时间:2023-10-16

我不确定如何读取有关读取文本文件的特定信息点。我要做的是。

  1. 从其输入(CIN>>用户ID)获取用户ID
  2. 程序检查ID是否存在于数据库中(读取.txt文件)
  3. 如果存在ID,请继续进行下一个部分
  4. 其他,cout错误消息

    //Example text from the file:

    12345678 23456789 34567890 45678901 etc. etc. etc.

在这里,如果用户输入" 12345678",我想了解如何允许C 在.txt文件中专门扫描12345678。因此,生成" 识别"消息。"消息。还是有人可以慷慨地将我引导到适当的链接?

您将要使用std :: string :: find。

示例:

if (fullString.find(partOfString) != std::string::npos) {
    std::cout << "found!" << endl;
}

因此,在您的示例中,您所使用的文本文档的行将是fullString,输入的用户ID将是零件。您也可以直接与

之类的东西进行直接比较
if (userString == lineFromFile)
{
    //do something
}

"在.txt文件中专门扫描123456" - 您不能。您拥有的是文本文件,而不是数据库。如果您的文件很大,我认为解决方案将是使用数据库(例如SQLITE),并让它为您生成索引。然后,您可以查询数据库中的任何匹配XYZ的用户ID。

假设您知道如何使用fstream and whats打开文件,则可以做一些段循环。

ifstream yourFile;
int userID, wantedID;
bool found = false;
//open file
while(yourFile >> userID && found == false){ //this says while there is numbers that can be put into UIN, do this. This way it won't keep trying after it has run out of numbers, and will also stop if/when it is found, whichever comes first.
    if(UserID == wantedID){
        found = true;
    }
 }

因此,这将允许的操作是搜索整个文件以查找ID,而当发现它时停止搜索。然后,您可以按照自己的意愿来完成您的意愿,尽管您也很可能仍然希望在使用UserId时检查发现的布尔值,以防目前没有找到并耗尽数字。