0
我最近開始學習C++。我寫這個程序根據用戶輸入輸出數字。在我向用戶詢問整數以確定輸出之前,我發現我可以使用getline從用戶那裏獲得一個字符串。我的問題是,現在無論用戶輸入什麼,程序總是輸出26.2,當它輸出其他東西。我如何只輸入「apple」輸出26.2,只輸入「orange」輸出12.9,只輸入「kiwi」輸出62.6等?C++ getline和if/else if語句不按我的意圖工作
#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();
}
}
解決了這個問題。謝謝! – user2530088