首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何迭代txt文件并将行存储在变量c++中

如何迭代txt文件并将行存储在变量c++中
EN

Stack Overflow用户
提问于 2020-04-26 00:02:30
回答 1查看 68关注 0票数 0

我正在寻找一种从txt中获取行并将它们存储在c++中的变量的更简单的方法。在我的txt文件中,一组3行表示一个想法--我的txt文件的示例如下:(包含一个想法)

约翰·史密斯

汽车,海滩,游泳

我叫约翰,我是一名教师。

下面是我的代码,它将每一行存储在向量中

代码语言:javascript
运行
复制
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文件包含以下内容

约翰·史密斯

汽车,海滩,游泳

我叫约翰,我是一名教师。

约翰苹果

狗,猫,游泳

我叫约翰,我是个商人

约翰·阿林

汽车,清洁,动物园

我叫约翰,我是个渔夫

在我的代码中,我需要以下内容

代码语言:javascript
运行
复制
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个想法,我需要重复很多次。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-26 00:18:19

如果直接填充Ideas的向量,则不需要字符串的向量。在代码更改最少的情况下,您可以将while循环更改为

代码语言:javascript
运行
复制
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。如果您编写了一个以这三个字符串为参数的构造函数,那么循环可能如下所示:

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
for (size_t i=0; i< inputText.size(); i+=3) {
    name = inputText[i];
    keyword = inputText[i+1];
    cont = inputText[i+2];
    // ...etc...
}

通常,当您认为需要多次编写相同的代码时,唯一的区别是索引,答案是循环。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61434176

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档