我最近开始学习 C++。我编写了这个程序,它根据用户输入输出数字。在我向用户询问整数以确定输出之前,但后来我发现我可以使用 getline 从用户那里获取一个字符串。我的问题是,现在无论用户输入什么,程序在应该输出其他内容时总是输出 26.2。如何只输入“apple”输出 26.2,只输入“orange”输出 12.9,只输入“kiwi”输出 62.6,等等?
#include <iostream>
#include <string>
using namespace std;
struct fruit {
float apple;
float orange;
float kiwi;
float tangerine;
float grape;
int banana;
};
int main()
{
string apple, orange, kiwi, tangerine, grape, banana;
fruit percentage;
fruit *ptr;
percentage.apple = 26.2;
percentage.orange = 12.9;
percentage.kiwi = 62.6;
percentage.tangerine = 18.3;
percentage.grape = 41.8;
percentage.banana = 13;
ptr = &percentage;
cout<<"Information from the USA in 2004.\n1. apple 2. orange 3. kiwi 4. tangerine 5. grape 6. banana\n";
if ( getline ( cin, apple ) ) {
cout<< ptr->apple;
cin.get();
}
else if ( getline ( cin, orange ) ) {
cout<< ptr->orange;
cin.get();
}
else if ( getline ( cin, kiwi ) ) {
cout<< ptr->kiwi;
cin.get();
}
else if ( getline ( cin, tangerine ) ) {
cout<< ptr->tangerine;
cin.get();
}
else if ( getline ( cin, grape ) ) {
cout<< ptr->grape;
cin.get();
}
else if ( getline ( cin, banana ) ) {
cout<< ptr->banana;
cin.get();
}
else {
cout<<"Error, invalid input.";
cin.get();
}
}