You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++数组输入限制问题:使用do while循环无法限制输入项至5个

数组输入限制为5个条目:解决do while循环失效问题

嘿,我看你遇到了个小问题——想用do while循环把数组输入限制在5个条目,但输入完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和输入逻辑在这里...
}

问题出在哪?

  • 数组大小不匹配:你定义的sItems[4]和iItemPrice[4]只能容纳4个元素,就算循环允许输入5个,也会触发数组越界的未定义行为,这本身就和你要输入5个条目的需求矛盾。
  • 循环退出条件错误:do while循环的终止条件应该检查当前已输入的条目数iNumOfItems是否达到5,否则循环会一直执行下去。

修复后的代码示例

首先调整数组大小到5,然后修正do while的逻辑:

#include "stdafx.h"
#include <string>
#include <conio.h>
#include <iostream>
#include <array>
using namespace std;

// 把数组大小改成5,刚好容纳5个条目
string sItems[5] = {};
string sChoice = "";
int iItemPrice[5] = {};
int iNumOfItems = 0;
int iMenuChoice = 0;
int iCount = 0;

int main() {
    do {
        // 示例输入逻辑,你可以替换成自己的菜单/输入流程
        cout << "请输入第" << iNumOfItems + 1 << "个商品名称: ";
        cin >> sItems[iNumOfItems];
        cout << "请输入该商品价格: ";
        cin >> iItemPrice[iNumOfItems];
        
        iNumOfItems++; // 每次输入后,已输入条目数加1
    } while (iNumOfItems < 5); // 当条目数小于5时继续循环
    
    // 输入完成后的逻辑,比如打印所有条目
    cout << "\n你输入的5个商品信息:\n";
    for (int i = 0; i < 5; i++) {
        cout << "商品" << i+1 << ": " << sItems[i] << ",价格: " << iItemPrice[i] << endl;
    }
    
    return 0;
}

关键说明

  • 数组大小必须和你要限制的条目数匹配,避免越界风险;
  • do while循环的条件iNumOfItems < 5会在每次输入后检查,当输入满5个时,iNumOfItems变成5,循环就会终止;
  • 记得在每次输入完成后递增iNumOfItems,不然循环条件永远不会满足终止要求。

内容的提问来源于stack exchange,提问作者user5623123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:53:16