【问题标题】:How to input numbers using auto loop in c++如何在 C++ 中使用自动循环输入数字
【发布时间】:2021-12-03 09:38:25
【问题描述】:

如何在 c++ 中使用自动循环输入数字

例如我有汉堡、油炸和苏打水的产品

#include <iostream>
#include <string>
#include <vector>


int main(){
    
    
    std::vector<std::string> products = {"burgers","fries","sodas"};
    std::vector<int> numbers = {};
    int a;
     for (auto n : products)
        std::cout <<"Enter number of "<< n << ": \n";
        std::cin >>a;
        numbers.push_back(a);

    return 0;
}

运行此代码后,这是输出

Enter number of burgers:
Enter number of fries:
Enter number of sodas:
1 // this is the only input

我想要这样的输出

   Enter number of burgers:
    1 // input
    Enter number of fries:
    1 // input
    Enter number of sodas:
    1 // input

【问题讨论】:

  • 你快到了:不要在你的 for 循环中使用 python 语法,你需要一个额外的范围。这意味着添加 { }。还可以考虑制作 auto n, const auto& n (它将避免额外复制字符串。

标签: c++ vector auto


【解决方案1】:

您需要在整个循环体周围放置大括号。不像Python,缩进不标记循环体:

     for (auto n : products) {
        std::cout <<"Enter number of "<< n << ": " << std::endl;
        std::cin >> a;
        numbers.push_back(a);
     }

【讨论】:

  • 我也建议不要复制products中的字符串,所以for (auto&amp; n : products)
  • @ted 所以const auto&amp; 在这种情况下就足够了,不是吗?
  • @πάνταῥεῖ 是的,更好:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 2015-01-30
相关资源
最近更新 更多