C++ 从文本文件中读取每两行,并且在矢量中是安全的

C++ Read every second line from a text file and safe in vector

本文关键字:安全 两行 文件 文本 读取 C++      更新时间:2023-10-16

我正在做一个小的"翻译"项目。我有这个文本文件,看起来像这样:

friend
amigo
mother
madre
telephone
teléfono

如您所见,第一行是英语单词,以下是要翻译的单词。我想将每个英语单词保存在一个向量中,将每个西班牙语单词保存到另一个向量中。我的问题是我不知道如何跳过这些行。

向量不是您的最佳选择。使用std::map这对字典来说真的很好,因为其中的元素是有序且唯一的,这确实是一个不错的选择,而不是使用两个向量将单词与其定义分开:

#include <map>
#include <iostream>
#include <string>
int main()
{
std::map<std::string, std::string> content;
std::ifstream in("Data.txt");
std::string word, definition;
while (std::getline(in, word) && std::getline(in, definition))
content[word] = definition;
for (const auto& p : content)
std::cout << p.first << " : "
<< p.second << std::endl;
std::cout << std::endl;
// To search for a word in dictionary:
std::string search = "mother";
auto ret = content.find(search);
if (ret != content.cend())
std::cout << search << " : n" <<
ret->second << std::endl;
else
std::cout << search << " : was not found in dictionary!" << std::endl;

std::cout << "n";
}

我不知道你的意图是什么,也不知道你尝试过什么。但我希望这有所帮助。

#include <iostream>
#include <vector>
#include <string>
using namespace std; 
int main(){
string array[10] = {"friend", "amigo", "mother", "madre", "telephone", "teléfono"};
vector<string> englishWords;
vector<string> spanishWords;
for(int i = 0; i < 10; i+=2){
englishWords.push_back(array[i]);
}
for(int i = 1; i < 10; i+=2){
spanishWords.push_back(array[i]);
}
for(int i = 0; i < englishWords.size(); i++){
cout << englishWords[i] << endl;
}
for(int i = 0; i < spanishWords.size(); i++){
cout << spanishWords[i] << endl;
}
}

我的问题是我不知道如何跳过这些行。

这里有一个想法:假设文件中总是有一个英语和一个西班牙语单词(或行(交替出现,你可以保留一个布尔变量is_english来表示当前单词(或行(的语言。它最初设置为true,假设第一个单词(或行(是英文的,然后设置为falsetruefalse等,或者每次阅读一个新单词(或行(。在每次迭代中,如果is_englishtrue,则将当前单词(或行(附加到English向量。否则,追加到Spanish矢量。下面给出了代码供您参考。

假设您有这样的文件:

friend
amigo
mother
madre
telephone
teléfono
#include <iostream>
#include <fstream>
#include <vector>
int main(){
std::ifstream in("./input.txt");
if(!in){
std::cout<<"Error opening the file! Maybe the file does not exist!";
return 0;
}
std::string one_line;
std::vector<std::string> english, spanish;
bool is_english = true; // Variable to denote current word (starts with english)
while(in.eof()==0){ // Read until end of file
getline(in,one_line);
if(is_english) // If english
english.push_back(one_line);
else // Otherwise, spanish
spanish.push_back(one_line);
is_english = !is_english; // Flip boolean variable value
}
std::cout<<"English words:n";
for(const auto i:english)
std::cout<<i<<std::endl;
std::cout<<"nSpanish words:n";
for(const auto i:spanish)
std::cout<<i<<std::endl;
return 0;
}

输出

English words:
friend
mother
telephone
Spanish words:
amigo
madre
teléfono