如何逐行从文件中获取单词,并在C++中用分号分隔?
How do I get words from a file line by line and seperated by a semicolon in C++?
我有下面写的代码。我正在尝试建立一个从德语到英语的词典。我有一个文本文件上的所有单词,用分号(大约 100 行(分隔,行的第一部分是德语单词,分号之后是英文翻译("Hund;狗》(。如何获取第一个单词并将其存储在变量中,忽略分号,然后将第二个单词存储在单独的变量中?
ifstream myfile("tiere_animals.txt");
if (myfile.is_open())
{
Entry Animal[661];
while (getline(myfile, line, ';'))
{
line2.push_back(';');
line2.clear();
line3.append();
}
myfile.close();
如何获取第一个单词并将其存储在变量中,忽略分号,然后将第二个单词存储在单独的变量中?
只需向上读取直到;
,然后向上读取直到换行符。
std::string english, german;
while (std::getline(myfile, german, ';') && std::getline(myfile, english, 'n')) {
std::cout << german << " in english is: " << english << "n";
}
您可以使用std::regex
:
#include <regex>
#include <streambuf>
#include <fstream>
using German = std::string;
using English = std::string;
std::vector<std::pair<German, English>> ParseFile(const std::string& filename)
{
std::fstream f{filename, std::fstream::in};
if (!f.is_open())
throw std::exception("failed to open the file");
// given you said that there are no motre than 100 lines, you can read the whole file at once
std::string fileContent{std::istreambuf_iterator<char>(f),
std::istreambuf_iterator<char>()};
std::regex pat{R"((?:(w+);s(w+)n))"}; \ suppose you have a format like "German; English(end of line)"
std::regex_iterator start{fileContent.cbegin(),
fileContent.cend()},
end{};
std::vector<std::pair<German, English>> out;
while (start != end)
{
const std::smatch& sm = *start;
// may check here if subgroups mathced.
out.emplace_back(sm[1], sm[2]); // sm[0] is a main group.
++start;
}
return out;
}
但是您需要正确格式化文件。
对于那些不喜欢 STL 正则表达式的人:在这种特殊情况下,没有关于内存使用或时间效率的明确限制。 除此之外,std::regex
还引入了可扩展性,因为您不需要更改代码而不是模式。因此,您可以轻松地将解析算法应用于具有其他布局的文件;
// can be used as a functor
class Parser
{
std::regex pattern_;
public:
Parser(std::regex pattern)
: pattern_(pattern)
{}
static std::vector<std::pair<German, English>> Parse(const std::string& filepath); // see above;
operator std::vector<std::pair<German, English>>(const std::string& filepath) const
{
return Parse(filepath);
}
}
您可以先阅读整行,然后将其单词分开:
ifstream myfile("tiere_animals.txt");
if (myfile.is_open()) {
string line, german, english;
while (getline(myfile, line)) {
istringstream iss(line);
getline(iss, german, ';');
getline(iss >> ws, english);
...
}
myfile.close();
相关文章:
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 在函数内部的声明中初始化数组,并在外部使用它
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 缓存std::数组的选定元素,并在c++中自动保持其一致性
- 定义C++新的环境变量并在 bat 文件中使用它
- Visual Studio 2017 停止工作,并在打开后显示许多控制台窗口
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 在 c++ 中模拟输入并在 JAVA 中读取它?
- 是否有必要获取锁并在不需要唤醒线程时通知condition_variable?
- 将通用对象传递给 Rust 并在使用后传递回 C++ 进行销毁
- 动态获取 esp32 的 mac 地址并在以太网库中使用它.
- 从.txt文件中读取浮点型数字并在公式中使用它们
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 在C++的头文件中使用常量并在程序中询问其地址的任何潜在危险
- C++ 和 Boost.Python - 如何将变量公开给 python 并在循环中更新它?
- 如何在组合框中列出所有可用的 VCL 样式,并在组合框更改事件中应用该样式C++生成器?
- 是否可以在文本文件中找到最长单词的长度,并在同一个文本文件中读取,只需 1 个 while 循环?
- 初始化类中的指针数组,并在另一个类中检索它