从文本文件中读取两列
read two columns from a text file
string dictionary;
ifstream in;
in.open("Q3.dic");
while(!in.eof())
{
getline(in, dictionary);
cout << dictionary <<endl;
}
这是我用来读取文本文件的内容,如下所示:
you vous
today aujourd'hui
good bon
good morning bonjour
afternoon après-midi
good evening bonsoir
much beaucoup
is est
注意:英语短语与其法语翻译之间用制表符分隔。
我要知道的是,是否可以将每列读取到两个不同的变量?
我试过了:
in >> english >> french;
cout << english << french <<endl;
但我遇到的问题是三个词的行。
std::getline()
接受第三个参数 - delim
- 分隔符字符,如果将其指定为第一次调用的't'
(制表符),则应获得所需的结果:
std::ifstream in("Q3.dic");
for (std::string english, french;
std::getline(in, english, 't') && std::getline(in, french);
)
{
std::cout << "English: " << english << " - French: " << french
<< std::endl;
}
对于那些包含多个制表符的行,您需要修剪字符串,但我声明这超出了这个问题的范围!
输出:
English: you - French: vous
English: today - French: aujourd'hui
English: good - French: bon
English: good morning - French: bonjour
English: afternoon - French: après-midi
English: good evening - French: bonsoir
English: much - French: beaucoup
English: is - French: est
我想你想使用类似 std::map<std::string,std::string>
的东西,其中 yo 有一个词作为特定语言的关键(请阅读评论中的解释):
std::map<std::string,std::string> dictionary;
ifstream in;
in.open("Q3.dic");
std::string line;
while(getline(in, line)) { // Read whole lines first ...
std::istringstream iss(line); // Create an input stream to read your values
std::string english; // Have variables to receive the input
std::string french; // ...
if(iss >> english >> french) { // Read the input delimted by whitespace chars
dictionary[english] = french; // Put the entry into the dictionary.
// NOTE: This overwrites existing values
// for `english` key, if these were seen
// before.
}
else {
// Error ...
}
}
for(std::map<std::string,std::string>::iterator it = dictionary.begin();
it != dictionary.end();
++it) {
std::cout << it->first << " = " << it->second << std::endl;
}
请参阅代码的实时工作示例。
根据我在代码注释中的注释,您可能已经注意到可能需要处理非唯一english -> french
翻译。在某些情况下,字典中的一个english
关键字可能具有多个关联的翻译。
你可以克服这一点,要么像这样声明你的字典
std::map<std::string,std::set<std::string>>> dictionary;
或
std::multi_map<std::string,std::string> dictionary;
相关文章:
- 如何从具有两列的.txt文件创建并行数组?
- 从两列中选择一个数字并进行计算
- 通过列读取文本文件,并显示列值的所有数组
- 如何使用两列C 从文本文件中填充向量
- 如何从文本文件中的特定列读取数据
- 在 QTableView 中跨两列跨越标题
- 两次读取指针就是给出垃圾值
- 有没有一种方法可以在两列中显示我的素数列表输出
- 以两列c++显示数据
- 交换由向量表示的矩阵中的两列
- 从具有两列的文件中加载二维阵列
- 关于具有两列并支持CRUD操作的C++数据结构的建议
- 逐列读取文本文件c++
- 两次读取std::cin的输入
- 如何获取具有两列模型的QComboBox的当前值
- 将文件列读取到数组中
- 用c++从文件中逐列读取数据
- 连续两次读取套接字,第二次读取不起作用
- 将两列的文件读入一个数组
- 从文本文件中读取两列