【问题标题】:How to add a list to a string?如何将列表添加到字符串?
【发布时间】:2022-07-28 23:54:24
【问题描述】:

我正在尝试将列表添加到字符串中。

int main() {
std::cout << "Hello, welcome to Jay's Coffee!!\n";

std::string name; std::cout <<"What is your name "; std::cin >> name;
  
std::cout <<"Hello " << name << ", thank you so much for coming in today";

std::list <std::string> menu = {"Black Coffee" "Espresso" "Latte" "Cappucino"};
std::cout << name <<",what would you like from our menu today? Here is what we are serving.\n" << menu;

}

返回

invalid operands to binary expression ('basic_ostream<char>' and 'std::list<std::string>' (aka 'list<basic_string<char>>'))

【问题讨论】:

  • 没有运算符
  • 标准容器没有输入或输出操作符。如果你想做cout &lt;&lt; container,你需要自己写

标签: c++


【解决方案1】:

列表没有operator&lt;&lt;。你必须写一个循环。例如

for (auto item : menu)
{
     std::cout << item << '\n';
}

如果您仔细考虑一下,很明显为什么您必须自己执行此操作。您如何分隔列表项?我选择将每个项目放在一个新行上。您可以选择用逗号或空格或一些花哨的格式分隔它们。因为没有明显的单一方法来打印列表,所以 C++ 库中没有预定义的方法。

【讨论】:

    【解决方案2】:

    错误消息表示您尝试使用的运算符 std::list<std::string> 定义。

    你还需要用逗号分隔初始化列表中的字符串。

    std::list <std::string> menu = {"Black Coffee", "Espresso", "Latte", "Cappucino"};
    

    例如,只需使用基于范围的 for 循环

    std::cout << name <<",what would you like from our menu today? Here is what we are serving.\n";
    
    for ( const auto &s : menu )
    {
        std::cout << s << '\n';
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-12
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 2017-10-09
      • 2011-09-10
      • 2018-08-12
      • 2014-07-05
      相关资源
      最近更新 更多