Search code examples
c++arraysfunctionstructure

How to fix "error: expected primary -expression before ')' token" in c++?


I am writing this code, and I have 2 structures and 1 function. The function takes in one of the structures as reference and uses the variables in it. The problem is that I keep getting the following 2 errors:

error: expected primary-expression before ')' token
error: 'arrayDrink' was not declared in this scope

I don't know what I am doing wrong.

I tried the other structure too, but I keep getting this error:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>

using namespace std;
const unsigned int maxDrinkItems = 20;

struct DrinkItem
{
    unsigned int id;
    string name;
    double price;
    unsigned int NumDrinksOfSameType;
    unsigned int drinksPurchased = 0;

};

struct DrinkMachine
{
    unsigned int versionNumber = 1;
    unsigned int totalDrinks;
    unsigned int arrayDrink[maxDrinkItems];
};

bool create(DrinkMachine &drinkMachine)
{
    ifstream inputFile;
    inputFile.open("drink_machine.txt");

    if(inputFile.fail())
    {
        return false;
    }
    else
    {

        while (inputFile.eof() || drinkMachine.totalDrinks == 20)
        {
            inputFile >> drinkMachine.totalDrinks;

            for (int i = 0; i < drinkMachine.totalDrinks; i++)
            {
                inputFile >> arrayDrink[i].name;
                inputFile >> arrayDrink[i].price;
                inputFile >> arrayDrink[i].NumDrinksOfSameType;
            }

        }

        inputFile.close();
        return true;
    }

}

here I call the function:

int main()
{
    create(DrinkMachine);

    return 0;
}

I want it to take in data from the file and put it into the array of structures, but I keep getting errors.


Solution

  • The condition in the while loop doesn't work the way you think.

    while (inputFile.eof() || drinkMachine.totalDrinks == 20)
    

    When doing input extraction in a loop you should first do the extraction, check if it succeeds, then continue. eof() checks if the eofbit (end-of-stream bit) in the stream is set, which occurs when the previous extraction failed. Typically when doing extraction you check stream validity with fail().

    while (inputFile >> drinkMachine.totalDrinks && !inputFile.fail() && drinkMachine.totalDrinks == 20)
    

    We can get rid of !inputFile.fail() since every stream has a built in operator bool() so it checks fail() implicitly:

    while (inputFile >> drinkMachine.totalDrinks && drinkMachine.totalDrinks == 20)
    

    Your other issues are pointed out by Acorn.