有没有办法在C 中扫描TXT文件中的单词或名称

Is there a way to scan a txt file for a word or name in c++?

本文关键字:单词 文件 扫描 有没有 TXT      更新时间:2023-10-16

因此,我试图在游戏开始时进行登录,并且已经对名称和密码的注册进行编程。但是,有没有办法扫描文件中的一个用户名之一?

:)预先感谢您。

c 中有"在文件中找到一个单词":

typedef std::istream_iterator<std::string> InIt;
if (std::find(InIt(std::ifstream("file.txt") >> std::skipws), InIt(), word) != InIt())
{
    std::cout << "the word '" << word << "' was found in 'file.txt'n";
}

为此,需要通过whitespace界定wordstd::istream_iterator<std::string>类从其构造的流中读取std::string类型的对象,并使迭代器访问相应的序列。默认结构的std::istream_iterator<std::string>()用于指示序列的结尾。std::find()只是标准算法之一,在序列中寻找与其最后一个参数相匹配的对象,在上述情况下word

代码有点奇怪的是使用std::ifstream对象:由于结果只是布尔表达式,因此使用了临时的std::ifstream。由于tsd::istream_iterator<std::string>的构造函数将std::istream&作为构造函数参数,并且临时性不能绑定到非const参考,因此插入了操纵器(std::skipws):此操作除了返回非const引用临时std::ifstream。/p>

不是"在文件中找到单词"函数,否。您必须打开,读取文件并扫描您已读取的文件的每个部分(例如行,块)中的单词,然后关闭文件。

以文本模式打开文件,然后按行读取该文件。对于每行,将其扫描以为您要寻找的单词。

就是这样。我知道您没有单一的功能可以打电话。

$ cat names.txt 
user1
user2
user3

$ cat c.cc
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main ()
{
    string STRING;
    const char *USERNAME = "user1";
    ifstream infile;
    infile.open ("names.txt");
    while(!infile.eof())
    {
        getline(infile,STRING); 
        if (strcmp(USERNAME,  STRING.c_str()) == 0) 
                cout<<STRING;
    }
    infile.close();
    return 0;
}

$ ./c
user1

如果要拥有

,请使用strncmp
username1 password1
username2 password2