需要将可以输入到数组中的项目数量限制为 5。我想我会使用 do while 循环,但即使输入了 5 个项目,它也会继续。任何帮助将不胜感激
#include "stdafx.h"
#include <string>
#include <conio.h>
#include <iostream>
#include <array>
using namespace std;
string sItems[4] = {};
string sChoice = "";
int iItemPrice[4] = {};
int iNumOfItems = 0;
int iMenuChoice = 0;
int iCount = 0;
int main()
{
cout << "--------- Welcome to the program ---------\n\n Please pick from an option below: \n 1: Enter new items \n 2: Change item prices \n 3: Input sold items \n 4: Receipt for previous items sold\n ";
cin >> iMenuChoice;
switch (iMenuChoice)
{
case 1:
{
do {
cout << "--------- ENTER NEW ITEMS ---------\n\nPlease enter the item Name: ";
cin >> sItems[iCount];
cout << "\nPlease enter the price of: " << sItems[iCount] << "\n";
cin >> iItemPrice[iCount];
cout << "\nWould you like to enter another item? Y/N \n";
cin >> sChoice;
if (sChoice == "Y" || sChoice == "y")
{
++iCount;
++iNumOfItems;
}
} while (sChoice == "Y" || sChoice == "y" || iNumOfItems < 5);
cout << "you have entered the maximum ammount of items";
}
}
_getch();
return 0;
}
最佳答案
循环条件sChoice == "Y" || sChoice == "y" || iNumOfItems < 5
意思是:
- 只要用户回答“Y”就循环
- 但至少 5 次,无论用户回答如何
如果你想要一些其他逻辑,比如最多循环 5 次,那么你可以在代码中反射(reflect)出来。
同时检查故障。如果在cin
时输入一个字符期望一个数字,它将进入失败状态,所有后续输入尝试都将失败。
do {
cout << "--------- ENTER NEW ITEMS ---------\n\nPlease enter the item Name: ";
cin >> sItems[iCount];
cout << "\nPlease enter the price of: " << sItems[iCount] << "\n";
if (!(cin >> iItemPrice[iCount]))
break;
cout << "\nWould you like to enter another item? Y/N \n";
cin >> sChoice;
++iCount;
++iNumOfItems;
} while ((sChoice == "Y" || sChoice == "y") && iNumOfItems < 5);
并从4
增加数组大小至 5
如果你想支持 5 个项目:
string sItems[5];
int iItemPrice[5];
关于c++ - 限制项目条目 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49555756/