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

在C++发票程序中用for/while循环实现字符串与整数映射的问题

解决方案:用循环关联商品选择与名称并实现选择反馈

我们可以用数组存储商品名称,结合for/while循环替代三元运算符或switch,同时完成选择后的商品展示功能,完全贴合你不用switch、强化循环练习的需求。

核心实现思路

  1. 用数组统一存储商品列表,让选择的整数与数组索引形成对应关系(选择1对应数组索引0,以此类推)
  2. 用for循环遍历数组,完成选择值到商品名称的映射
  3. 用while循环验证输入有效性,强化循环的实际应用场景
  4. 补充选择后的商品展示逻辑

修改后的完整代码

#include <iostream>
#include <string>
using namespace std;

int getIntValue(string toInput){
    cout << "Please enter " << toInput << ": ";
    int value;
    cin >> value;
    return value;
}

string choiceToItem(int choice){
    const string items[] = {"Bread", "Milk", "Eggs", "Deodorant", "Cheese"};
    const int itemCount = sizeof(items)/sizeof(items[0]);
    
    // 用for循环匹配选择与商品
    for(int i = 0; i < itemCount; ++i){
        if(choice == i + 1){ // 选择1对应数组第0位元素
            return items[i];
        }
    }
    return "Invalid Item";
}

int main()
{
    const int MinGroceryValidChoice = 1;
    const int MaxGroceryValidChoice = 5;

    // 用for循环打印商品选项列表
    for (int choice = MinGroceryValidChoice; choice <= MaxGroceryValidChoice; ++choice){
        cout << choice << ", " << choiceToItem(choice) << endl;
    }
    
    int userChoice = getIntValue("your item choice");
    
    // 用while循环校验输入合法性
    while(userChoice < MinGroceryValidChoice || userChoice > MaxGroceryValidChoice){
        cout << "Invalid choice! Please try again." << endl;
        userChoice = getIntValue("your item choice");
    }
    
    // 展示用户选择的商品
    cout << "You selected: " << choiceToItem(userChoice) << endl;

    return 0;
}

关键细节说明

  • 数组存储+for循环映射:把商品名存入数组后,通过for循环遍历匹配选择值,彻底替代了原有的三元运算符逻辑,完全依赖循环实现关联
  • while循环输入校验:在获取用户选择后,用while循环持续提示输入,直到用户输入合法值,强化了循环的条件判断应用
  • 选择反馈逻辑:在输入校验通过后,直接调用映射函数输出对应商品,完成你需要的选择后展示功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:17:29