簡體   English   中英

如何遍歷 txt 文件並將行存儲在變量 c++ 中

[英]how to iterate over txt file and store lines in variables c++

我正在尋找一種更簡單的方法來從 txt 中獲取行並將它們存儲在 c++ 的變量中。 在我的 txt 文件中,一組 3 行代表 1 個想法 我的 txt 文件的示例如下:(包含一個想法)

約翰·史密斯

汽車、海灘、游泳

我的名字是約翰,我是一名老師

這是我的以下代碼,它將每一行存儲在一個向量中

vector <string> inputText;
    string name, prop, keyword, cont;
    ifstream file;
    string line;
    file.open("input.txt");
if (file.is_open()) {
    string line;
    while (getline(file, line)) {
       inputText.push_back(line);
    }

    file.close();
    name = inputText[0];
    keyword = inputText[1];
    cont = inputText[2];

    idea.setID();
    idea.setProposer(name);
    idea.setKeywords(keyword);
    idea.setContent(cont);
    newIdea.push_back(idea);

}

我正在尋求一種更有效地將行存儲在變量中的方法,因為我想有多種想法。 在我當前的代碼中使用多個想法將導致代碼非常長且效率低下。 我的 txt 文件中的哪個想法將用完 3 行。 我的問題是,有沒有一種有效的方法可以將 txt 文件中的多個想法存儲在變量中,而無需使用索引。

編輯:這就是我所說的冗長而低效的代碼,例如說我的 txt 文件包含以下內容

約翰·史密斯

汽車、海灘、游泳

我的名字是約翰,我是一名老師

約翰蘋果

狗,貓,游泳

我的名字是約翰,我是一名商人

約翰里脊

汽車, 清潔, 動物園

我的名字是約翰,我是漁夫

比在我的代碼中我需要以下

idea.setProproser(inputText[0];
idea.setKeyword(inputText[1]);
idea.setContent(inputText[2]);
newIDea.push_back(idea);

idea.setProproser(inputText[4];
idea.setKeyword(inputText[5]);
idea.setContent(inputText[6]);
newIDea.push_back(idea);

那么如果我在文件中有 10 個想法,我需要重復很多次。

如果直接填充Idea的向量,則不需要字符串向量。 只需對代碼進行最少的更改,您就可以將 while 循環更改為

std::string name_line;
std::string keyword_line;
std::string content_line;
while (std::getline(file, name_line) && 
       std::getline(file,keyword_line) &&
       std::getline(file,content_line)) {
    Idea idea;
    idea.setID();
    idea.setProposer(name);
    idea.setKeywords(keyword);
    idea.setContent(cont);
    newIdea.push_back(idea);
}

但是,您應該使用構造函數來構造Idea 如果您編寫一個將這三個字符串作為參數的構造函數,則循環可能如下所示:

std::string name_line;
std::string keyword_line;
std::string content_line;
while (std::getline(file, name_line) && 
       std::getline(file,keyword_line) &&
       std::getline(file,content_line)) {
    newIdea.emplace_back(name_line,keyword_line,content_line);
}

PS:即使你留在字符串的向量,你也不需要寫“一個非常長和低效的代碼”。 就像您使用循環來填充字符串向量一樣,您可以使用循環來構造Idea s:

for (size_t i=0; i< inputText.size(); i+=3) {
    name = inputText[i];
    keyword = inputText[i+1];
    cont = inputText[i+2];
    // ...etc...
}

總是當你認為你需要多次編寫相同的代碼並且唯一的區別是索引時,答案是循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM