尝试制作一个可以打印发票的小程序。它需要 4 - 6 个不同的函数。然而,我遇到最困难的事情是试图将我的字符串值与整数联系起来并调用它们。
我想要做的是将我的整数值与字符串中的值联系起来。
注意: 我想在不使用开关值的情况下执行此操作,只需使用 for 或 while 循环。特别想要更多练习这些。
我的第一次尝试是尝试这样的事情:
int getIntValue(string toInput){
cout << "Please enter " << toInput << ": ";
int value;
cin >> value;
return value;
}
string choiceToItem(int choice){
return choice == 1 ? "Bread" :
choice == 2 ? "Milk" :
choice == 3 ? "Eggs" :
choice == 4 ? "Deoderant" :
choice == 5 ? "Cheese" :
"Invalid Item";
}
然后在int main()中:
int main()
{
const int MinGroceryValidChoice = 1;
const int MaxGroceryValidChoice = 5;
//we use for loops for known values
for (int choice = MinGroceryValidChoice; choice <= MaxGroceryValidChoice; ++choice){
cout << choice <<", "<< choiceToItem(choice)<< endl;
}
int choice = getIntValue("choice");
return 0;
}
我想让我的程序显示我的选择。只是朝着正确方向的一般观点将不胜感激。
您可以尝试使用枚举类,这些列表条目按从 0 开始的整数值升序排列。