【发布时间】:2021-04-29 23:01:13
【问题描述】:
当我尝试使用 'a' 选项并选择 12 时,向量只会添加 2:
num_vec's elements: 2 9 2 3 4 6 3 9 4 3 2 3 4 2 3
=====Menu=====
P - Print Numbers
A - Add a number
M - Display the mean of numbers
S - Display the smallest number
L - Display the largest number
Q - Quit the Program
Enter a choice: a
Enter number you'd like to add to num_vec: 12
num_vec's elements: 2 9 2 3 4 6 3 9 4 3 2 3 4 2 3 2
代码:
int main(){
std::vector<int> num_vec{8,6,4,3,2,7,9,6,2,3,8,3,2,4};
char choice;
do{
std::cout << "\n" << std::endl;
std::cout << "=====Menu=====" << std::endl;
std::cout << "P - Print Numbers" << std::endl;
std::cout << "A - Add a number" << std::endl;
std::cout << "M - Display the mean of numbers" << std::endl;
std::cout << "S - Display the smallest number" << std::endl;
std::cout << "L - Display the largest number" << std::endl;
std::cout << "Q - Quit the Program" << std::endl;
std::cout << "Enter a choice: ";
std::cin >> choice;
else if (choice == 'A' || choice == 'a'){
int num;
std::cout << "Enter number you'd like to add to num_vec: ";
std::cin >> num;
num_vec.push_back(num);
}
感谢任何帮助,对我来说很头疼,但应该很简单。另外,请不要使用没有用的 cmets,例如到目前为止的大多数。 典型的堆栈溢出自我移动。
【问题讨论】:
-
请张贴Minimal Reproducible Example,您的代码被截断,问题无法重现,而顶部唯一直接相关的是您执行
cin >> choice,其中choice是一个字符,在读取命令之前不会跳过空格,就像你可能想要的那样。 -
change
std::cout << num_vec.at(i)->std::cout << ii是向量中的值而不是索引。 -
auto i:num_veci 是元素值,而不是元素索引。 -
漏洞出现在您对
std::ignore的调用中。创建Minimal Reproducible Example 会帮助您找到它。 -
显然您没有注意到,即使是原始打印输出也与您的原始矢量不一样
标签: c++ arrays vector push-back