0

I started learning C++ recently. I wrote this program that outputs numbers based on user input. Before I was asking the user for integers to determine the output, but then I found out that I can obtain a string from the user using getline. My problem is that now no matter what the user inputs the program always outputs 26.2 when it should output other things. How do I make only typing "apple" to output 26.2, only typing "orange" to output 12.9, only typing "kiwi" to output 62.6, etc?

#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
  • 1
  • 1
  • 1

1 Answers1

2

You never make a comparison. Your if statements only say if (getline(...)). The getline() function takes a stream and a result string and returns the stream again. Let's take your first line for example:

if ( getline ( cin, apple ) ) {

getline(cin, apple) will take the next line from cin (the user input) and copy it into the string apple. Then it will return cin. Since cin is now the returned value in your if statement, the if statement checks to see if it's true or false. Obviously, cin is neither, but the system interprets it as true and executes your first statement always.

Now, as for how to fix this. You'll want to get the input once at the beginning of your program, for example:

string in;
getline(cin, in);

And then compare that variable in your if statements.

if (in == "apple") {
    // Do stuff for apples
} else if (in == "orange") {
    // Do stuff for oranges
} // etc
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116