0

Struct Problem 1.cpp

    // Struct Problem 1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include "structs.h"

double calculateEarnings(Advertising aDay);
void displayEarnings(int questionInstance, Advertising aDay);
void mainQuestions();

int _tmain(int argc, _TCHAR* argv[])
{
    mainQuestions();
    return 0;
}

double calculateEarnings(Advertising aDay)
{
    std::cout << aDay.usersClicked; //debug
    return aDay.totalAdsShown * aDay.usersClicked * aDay.averagePerAd;
}

void takeInData(int questionInstance, Advertising aDay)
{
    if (questionInstance == 0)
    {
        std::cin >> aDay.totalAdsShown;
    }
    else
        if (questionInstance == 1)
        {
            std::cin >> aDay.usersClicked;
        }
        else
            if (questionInstance == 2)
            {
                std::cin >> aDay.averagePerAd;
            }
    std::cin;
}

void mainQuestions()
{
    static Advertising aToday;
    aToday.totalAdsShown = 0;
    aToday.usersClicked = 0.00;
    aToday.averagePerAd = 00.00;

    std::cout << "Welcome! Please input the advertising data for today." << "\n";
    std::cout << "How many ads were shown today?" << "\n";
    takeInData(0, aToday);
    std::cout << "What percentage of users clicked our ads? (decimal form)" << "\n";
    takeInData(1, aToday);
    std::cout << "What were the average earnings per ad? (ex: 5.15)" << "\n";
    takeInData(2, aToday);

structs.h

    #ifndef STRUCTS_H
#define STRUCTS_H

typedef double percentage;
typedef double USD;

struct Advertising
{
    int totalAdsShown;
    percentage usersClicked;
    USD averagePerAd;
};

#endif

Basically, the data is not saved when called by 'cin'. I added a line to print the aDay.usersClicked value and it prints to 0. I am learning c++, so the problem is very basic. I appreciate all tips!

Thank you

1 Answer 1

2

Change this:

void takeInData(int questionInstance, Advertising aDay)

into this:

void takeInData(int questionInstance, Advertising& aDay)

and it will work. The reason is that in your version, the paramater aDay is passed-by-value; i.e. a copy of the argument is passed to the function. So anything that takeInData() does to its version of aDay is done in the copy. After takeInData() returns, the copy (and the information therein) is lost.

In the edited version, a reference to aDay is passed to the function. Now it will reference the variable that was passed, i.e. the variable in main(). Now all things takeInData() does, are stored in the value that is actually declared in main().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.