V. Martins V. Martins - 19 days ago 7
C++ Question

string undeclared identifier

I'm new with arrays, I wrote this piece of code here and I thought I had done everything syntax wise correctly. However, I get an

C2065 'string': undeclared identifier

As you can see I have my Prototypes set, and yet it still gives that error?

#include<iostream>
#include<string>

//Prototypes:
void getJars(string[], int[], int);
int getTotal(string[], int[], int);

using namespace std;

int main() {

string salsa[] = { "Mild", "Medium", "Sweet", "Hot", "Zesty" };
const int NUM = 5;

int jars[NUM];

getJars(salsa, jars, NUM);
getTotal(salsa, jars, NUM);



return 0;
}

void getJars(string salsa[], int jars[], int NUM) {



cout << "Salsa Sales Calulator...\n";
cout << "------------------------\n";
for (int i = 0; i < NUM; i++) {

cout << "Please Insert the Jar Amount for Each Salsa: ";
cout << salsa[i];
cout << " ";
cin >> jars[i];

cout << endl;
}


return;
}
int getTotal(string salsa[], int jars[], int NUM) {

int total;

for (int i = 0; i < NUM; i++) {

total += jars[i];
}

return total;
}


I looked up the error on here, however, the solution they had come up with was to add the prototypes which most people forget however I did not forget and it still gives the error? Could anyone help??

Answer

Exchange these statements

void getJars(string[], int[], int);
int getTotal(string[], int[], int);

using namespace std;

Should be

using namespace std;

void getJars(string[], int[], int);
int getTotal(string[], int[], int);

Also initialize variable total

int getTotal(string salsa[], int jars[], int NUM) {

    int total = 0;
    ^^^^^^^^^^^^^

    for (int i = 0; i < NUM; i++) {

        total += jars[i];
    }

    return total;
}

And update a typo

cout << "Salsa Sales Calculator...\n";
                     ^^^^^^^^^^^

And you can remove the return statement in function getJars because the function has return type void and the return statement is not required for this function.

Comments