c++ - 限制项目条目 C++

标签 c++ while-loop

需要将可以输入到数组中的项目数量限制为 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/

相关文章:

c++ - 如何在 C++ 中查找字符串中出现的字符串?

C++ 互斥体和 const 正确性

c++ - 如何使用 std::ostringstream 截断整型的宽度?

c++ - 在 DEBUG 模式下调整字节字段大小时发生访问冲突

linux - 意外标记附近的语法错误

c - 双 while 循环链表导致无限循环

c++ - 调用成员函数集到特定变体的正确 C++ 变体语法是什么?

php - 如何通过php从mysql中删除一行

Java程序跳过while循环

java - 重新启动程序/游戏