【问题标题】:Adding text at the beginning and at the end of each line在每行的开头和结尾添加文本
【发布时间】:2013-12-31 11:55:12
【问题描述】:

我对编程有点陌生,当人们搜索某些内容时,我正在制作过滤器。我正在使用 Code::Blocks 进行编码。 例如,我拿了一些口袋妖怪:

Ivysaur
Venusaur
Charmander
Charmeleon
Charizard
Squirtle
Wartortle
Blastoise
Caterpie
Metapod

例如,我想将这些口袋妖怪中的每一个添加到我的变量“矢量字符串 pokeList”中。

vector<string> pokeList;
pokeList.push_back("Bulbasaur");
Ivysaur
Venusaur
Charmander
Charmeleon
Charizard
Squirtle
Wartortle
Blastoise
Caterpie
Metapod

如何添加 "pokeList.push_back("");"到每一行而不是“手动”做,因为“手动”添加 700 个口袋妖怪真的很长...... PS:我不想创建一个包含列表的 .txt 文件。

谢谢。

【问题讨论】:

  • “手动”是什么意思?
  • 您没有将它们保存在文本文件中?您是否已经将它们放在源文件中?您必须已经将它们存储在某处,不是吗?
  • 嗯。在 Vi 中::%norm IpokeList.push_back("&lt;End&gt;");
  • 这听起来像是“如何在我的 IDE 中搜索/替换文本?”问题,与 C++ 无关。看起来 CodeBlocks 在搜索/替换中支持正则表达式,所以使用它。
  • @JoachimPileborg 我认为他在Stack Overflow AFAICT 上的帖子中有他们

标签: c++ codeblocks


【解决方案1】:

如果 Code::Blocks 使用了足够现代的编译器,您可以通过使用该语言中的更新功能来解决这个问题,而无需 IDE 技巧。在 C++11 中,您的示例可以写成:

auto pokeList = vector<string>{
    "Bulbasaur",
    "Ivysaur",
    "Venusaur",
    "Charmander",
    "Charmeleon",
    "Charizard",
    "Squirtle",
    "Wartortle",
    "Blastoise",
    "Caterpie",
    "Metapod"
};

http://ideone.com/b45OeD

【讨论】:

    【解决方案2】:

    你从哪里得到口袋妖怪列表?如果您有一个包含所有名称的文件,您可以读取该文件:

    #include <vector>
    #include <string>
    #include <iostream>
    #include <fstream>
    
    int main()
    {
        std::vector<std::string> pokeList;
    
        std::ifstream pokeFile("your file path/name here");
        if (pokeFile.is_open())
        {
            std::string str;
            while (std::getline(pokeFile, str))
            {
                pokeList.push_back(str);
            }
    
        } else
        {
            std::cout << "Unable to open file";
        }
    
    }
    

    现在您可以从外部编辑列表了。

    p.s 建议不要将像这样的巨大静态列表放在代码中,更容易将其放在单独的文件中。

    【讨论】:

    • 特别考虑到通过一次填充一个名称来“构建”列表是一种浪费时间。参见例如stackoverflow.com/questions/4268886/… 提供更好的方法(但您从外部文件读取的方式更加通用)。
    【解决方案3】:

    您可以使用指向这些字符串文字的指针创建一个静态数组,并使用它来初始化向量。例如

    #include <vector>
    #include <string>
    #include <iterator>
    
    const char * pokemons[] = 
    { 
       "Ivysaur",
       "Venusaur",
       /* other pokemons */ 
    
       "Metapod"
    };
    
    int main()
    {
       std::vector<std::string> pokeList( std::begin( pokemons ), std::end( pokemons ) );
    }
    

    您可以将数组定义放在单独的头文件中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多