有没有办法在C 中扫描TXT文件中的单词或名称
Is there a way to scan a txt file for a word or name in c++?
因此,我试图在游戏开始时进行登录,并且已经对名称和密码的注册进行编程。但是,有没有办法扫描文件中的一个用户名之一?
:)预先感谢您。
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界定word
:std::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
如果要拥有
,请使用strncmpusername1 password1
username2 password2
相关文章:
- 文本文件中的单词链表
- 在指针的帮助下,文本文件中单词的频率
- 我们如何在文本文件中找到C++中的几个单词?
- 是否可以在文本文件中找到最长单词的长度,并在同一个文本文件中读取,只需 1 个 while 循环?
- 按单词搜索文件,然后在C++中打印特定行数
- 如何检查流中文件的下一个单词是否为 alpha?
- 从文件中查找单词并替换到其他文件中
- 该程序将.csv文件中的一系列单词放入数组中,然后随机生成句子.但它不起作用
- 如何逐行从文件中获取单词,并在C++中用分号分隔?
- 如何从文件中读取单词,将它们分配给数组并分析其内容?
- 如何在 c++ 中从文本文件中获取特定单词?
- 我们如何重新制作程序以打开xml文件并在价格单词之后读取百分比值并更改此值
- 从之前添加的批处理文件中删除单词
- C++读取大文件并将其保存到字符串中,然后删除特定的随机单词
- C++ 如何检查哪些单词不在 2 个类似文件中
- 显示文件中具有最小给定元音数的单词
- 简单的二分搜索对我不起作用。我正在尝试从文本文件中搜索单词
- 使用结构数组计算文本文件中单词的出现次数C++
- 包含换行符分隔的单词的文件和C++中这些单词的字符串向量的大小是否相同?
- 将玩家输入与单词文件进行比较