在文本文档中查找特定行
Find specific lines in text document
我想创建一个小程序来更好地理解我需要的东西。
该代码可以将单词写入文本文档,按顺序在前一行下写入新行,并在重新启动程序后将行保留在那里。
现在,在向文件中添加一个新单词或短语之前,我想知道这个单词是否已经存在于我的文档中,如果存在,不要添加它,而是在输出时使exit等于一,从文件中读取它,这里的主要内容是在当前存在行的下方或上方找到行。例如:如果现有行索引为3,我希望看到+1行4或-1行2。如果文本文档中不存在新词,只需添加即可。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
std::ofstream outfile("doc.txt", std::ios_base::app);
int main()
{
std::string t;
for (int i = 0; i < 10; i++)
{
cout << "Add new phrase: " << endl;
std::getline(std::cin, t);
cout << t << endl;
outfile << t << std::endl;
}
_getch();
return 0;
}
编辑:
using namespace std;
std::ofstream outfile("doc.txt", std::ios_base::app);
int main()
{
int length = 100;
std::ifstream infile("doc.txt", std::ifstream::in);
infile.seekg(0, infile.end);
size_t len = infile.tellg();
infile.seekg(0, infile.beg);
char *buf = new char[len];
infile.read(buf, length);
infile.close();
std::string writtenStr(reinterpret_cast<const char *>(buf), len);
std::string t;
for (int i = 0; i < 10; i++)
{
std::getline(std::cin, t);
if (writtenStr.find(t) != std::string::npos)
{
cout << "Line [" << t << "] exist." << endl;
}
else
{
cout << "Line [" << t << "] saved." << endl;
writtenStr += t;
outfile << t << std::endl;
}
}
_getch();
return 0;
}
程序启动时,我会将文件读取为字符串。然后,每次我想添加一个新词时,都要检查这个短语的字符串。如果字符串中不包含短语,请将其添加到字符串和文件中,如果需要,还可以添加您选择的分隔符。例如:
int main()
{
// Read existing file into a string
std::ifstream infile("doc.txt", std::ifstream::in);
infile.seekg(0, infile.end);
size_t len = infile.tellg();
infile.seekg(0, infile.beg);
char *buf = new char[len];
infile.read(buf,length);
infile.close();
std::string writtenStr(reinterpret_cast<const char *>(buf), len);
// Open file for output
std::ofstream outfile("doc.txt", std::ios_base::app);
std::string t;
for (int i = 0; i < 10; i++)
{
// Get new phrase
std::getline(std::cin, t);
// Check if phrase is already in file;
if (writtenStr.find(t) == std::string::npos)
{
cout << "Could not add new phrase: " << endl;
cout << t << endl;
cout << "Phrase already exists in file." << endl;
}
else
{
cout << "Add new phrase: " << endl;
cout << t << endl;
writtenStr += t;
outfile << t << std::endl;
}
}
_getch();
return 0;
}
相关文章:
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 如何从文本文件中查找最常见的字母和出现次数?
- 在文本中查找半个单词"ABBA"的问题
- 在C++中查找文本中的模式
- 创建程序以从给定的.txt文件中查找文本,替换并计算单词
- 如何创建一个函数,该函数在文本中查找单词的匹配项,包括跳过
- 在大型 JSON 文件中查找文本
- 尝试在自定义 QT 创建器文本编辑器中创建查找和替换循环.我似乎无法设置光标位置
- 文本文件中的电话号码查找
- 如何在没有分隔符的大文本文件中查找所有字典单词
- C++查找文本和计数出现次数
- 在文本文件 C++ 中查找( ")
- Visual Studio,在(解决方案资源管理器的)某个筛选器内的所有文件中查找/替换文本
- 查找字符在标准输入文本中出现的次数
- 如何将文本(诗歌)拆分为行(字符串/字符[])并查找每个行的最后一个单词
- 文本处理以查找字符串的共存
- 查找文本文件中的行数,并使用此维度构造数据点
- 在Qt5/C++中向后查找文本文件(尾随文件)
- 如何在c++中查找文本文件中的特定单词?
- 查找文本"space"值(以像素为单位)