【发布时间】: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 (它将避免额外复制字符串。