So, I am currently working on a text-based RPG, and I've run into an odd issue working on the character's inventory. I am getting the following error:
qualified-id in declaration before '(' token
This error is located at the following line of code in my Inventory.cpp class:
void Inventory::addItem(Item *I){...}
Of course, I realize that this isn't enough information to go by, so here is all the coding for both Inventory.h and Inventory.cpp:
In Inventory.h:
#ifndef INVENTORY_H
#define INVENTORY_H
#include "Item.h"
#include <string>
const int BACKPACK_SIZE = 16;
class Inventory
{
public:
Inventory();
void addItem(Item *I);
std::string getInventory();
Item *backpack[BACKPACK_SIZE];
protected:
private:
};
#endif // INVENTORY_H
In Inventory.cpp:
#include "Inventory.h"
Inventory::Inventory(){
for(int i = 0; i < BACKPACK_SIZE; i++){
backpack[i] = nullptr;
}
}
std::string Inventory::getInventory(){
std::string allItems = "";
int counter = 1;
for(int i = 0; i < BACKPACK_SIZE; i++){
if(backpack[i] == nullptr){
continue;
}
else{
allItems += (counter + ".) " + backpack[i]->getName() + "\n");
counter += 1;
}
return allItems;
}
void Inventory::addItem(Item *I){ //THIS LINE IS WHERE THE ERROR APPEARS
for(int counter = 0; counter < BACKPACK_SIZE; counter++){
if(backpack[counter] == nullptr){
backpack[counter] == I;
break;
}
}
}
I've done my research, yet I simply cannot figure what on earth I am doing wrong. Any help is much appreciated! Side note: it would be appreciated if people would not spend their time commenting on other things I could change about my coding, but rather stick to this specific issue. Thank you!
This question will likely be closed as a typo, but I'd like to illustrate a comment from #john that may help you. (While also answering your question)
std::string Inventory::getInventory()
{
std::string allItems = "";
int counter = 1;
for(int i = 0; i < BACKPACK_SIZE; i++)
{
if(backpack[i] == nullptr)
{
continue;
}
else
{
allItems += (counter + ".) " + backpack[i]->getName() + "\n");
counter += 1;
}
return allItems;
}
Your code has been reformatted here so that opening and closing braces are indented to the same level.
You may notice that it's much more apparent that you are getting your error because of a missing brace.
Related
Out of range error for vectors in my code. What can I do to stop the error? I've checked so many forums.
I've already done some basic trials to see if something else was the problem. Starting at 0. Wrote the code from scratch again. Used other IDEs.
#include <iostream>
#include <vector>
#include "graph.h"
using namespace std;
graph::graph() {
count = 0;
}
void graph::addVertex(const Node node) {
vertices.push_back(node);
count++;
}
void graph::addEdge(const char from, const char to) {
vertices[from].edges.push_back(to);
vertices[to].edges.push_back(from);
}
void graph::print() {
unsigned int i = 0;
while (i < vertices.size()) {
cout << vertices[i].name << "->";
if (vertices[i].edges.size() > 0)
for (unsigned int j = 0; j < vertices[i].edges.size(); j++)
cout << vertices[i].edges[j];
cout << endl;
i++;
}
Results always lead me to line 1733 of the vector file, and I'm unsure if more error will come after fixing the error.
Thank you for everybody's responses, especially #user4581301, I messed around with it, and the output comes out as desired with this replacement for the addEdge function.
void graph::addEdge(const char from, const char to) {
if (vertices.size() == 0)
return;
for (int i = 0; i < vertices.size(); i++) {
if (vertices[i].name == from)
vertices[i].edges.push_back(to);
if (vertices[i].name == to)
vertices[i].edges.push_back(from);
}
}
this is my first post. Below the code of my implementation of a char Stack. Theoretically It should print f,g,h. But when I execute it, I can just see a long list of strange signs in the console. Is a compiler issue or code issue? Thanks.
#include <iostream>
using namespace std;
const int max_L = 10;
class Stack {
protected:
char array[];
int length;
public:
Stack(){length = 0;}
bool push(char c) {
if(length < max_L){
array[length] = c;
length++;
return(true);
}
else return(false);
}
void pop(){
if(length >= 1){
cout << array[length];
length--;
} else return ;
}
bool is_empty(){
return(length == 0);
}
void print(){
for(int i = 0; i < length; i++){
cout << array[i];
}
}
};
int main() {
Stack p1;
p1.push('f');
p1.push('g');
p1.push('h');`
p1.print();
return 0;
}
There are two problems in the code. As πάντα ῥεῖ said, the array has to be created with a size. The other problem is that push and pop aren't quite complementary. push puts the added value at array[length], then increments length. So after a call to push, length is the index of the next entry, i.e., the one that hasn't been put in yet. pop has to look at the previous entry, i.e., the one that was just put in. So the code for pop should decrement length before looking at array[length]. Change
cout << array[length];
length--;
to
length--;
cout << array[length];
I'm coming to you with a problem that has several different files involved. I'm not sure why I'm getting the error specified in the title. Let me put the files below and go from there.
DummyClient.cpp
#include "Gameboard.h" //for Gameboard
#include "Location.h" //for function prototypes
#include "zList.h" //for Zombies
#include <iostream> //for input/output stream
using namespace std;
void main()
{
srand(123456789);
Gameboard myGB;
myGB = Gameboard();
ZombieListClass();
ZombieRec zombieList[MAX_ZOMBIES];
PopulateZombies(zombieList[MAX_ZOMBIES]); // this throws the error here of "Error: identifier "PopulateZombies" is undefined"
}
zList.h
#ifndef ZLIST_H
#define ZLIST_H
#include "Location.h" // for list record
#include "ZombieRec.h"
#include "Gameboard.h"
class ZombieListClass
{
public:
ZombieListClass(); //default constructor
void PopulateZombies(ZombieRec zombieList[]);
bool IsInBounds(int row, int col);
private:
ZombieRec list[MAX_ZOMBIES]; //stores the items in the list
int length; //# of values currently in the list
int currPos; //position of current element
int strength; // health and attack units of a zombie
};
#endif
zList.cpp
#include "zList.h"
ZombieListClass::ZombieListClass() //default constructor
{
length = 0;
currPos = 0;
strength = 5;
LocationRec zombieLoc;
}
void ZombieListClass::PopulateZombies(ZombieRec zombieList[])
{
int row, col;
for (int i = 0; i < MAX_ZOMBIES; i++)
{
row = rand() % MAX_ROW + 1;
col = rand() % MAX_COL + 1;
while (!IsInBounds(row, col))
{
row = rand() % MAX_ROW + 1;
col = rand() % MAX_COL + 1;
}
zombieList[i].currLoc.row = row;
zombieList[i].currLoc.col = col;
}
}
bool ZombieListClass::IsInBounds(int row, int col)
{
if (row == 0 || row == MAX_ROW + 1 || col == 0 || col == MAX_COL + 1)
{
return false;
}
else
{
return true;
}
}
Gameboard.h
#ifndef GAMEBOARD_H
#define GAMEBOARD_H
#include "Location.h"
#include "ZombieRec.h"
#include "zList.h"
const int MAX_ROW = 3; // total number of rows in the board
const int MAX_COL = 3; // total number of cols in the board
class Gameboard
{
public:
Gameboard();
private:
int boardSizeArr[MAX_ROW + 2][MAX_COL + 2];
}; // end Gameboard
#endif
and finally, Gameboard.cpp
#include "Gameboard.h"
Gameboard::Gameboard()
{
// Declares a board with a boundary along the outside
boardSizeArr[MAX_ROW + 2][MAX_COL + 2];
}
I'm not looking to be spoonfed and for somebody to solve my problem for me, I'm trying to figure out what I'm doing wrong so that the remainder of my project isn't as bumpy as it has been this whole time.
Looking back on my error, "identifer "PopulateZombies" is undefined", I can't imagine why it is. Could this have something to do with the scope of how I'm doing things? If I've left any code out (I didn't put everything in there but I think I have everything relevant) just let me know, I'm able to converse back and forth as long as this takes.
Thank you to everybody in advance that tries to help :)
-Anthony
In general, you call the function using a variable, instead of calling it directly if defined in a class:
ZombieListClass zombieList=new ZombieListClass(); // add a variable here
ZombieRec zombieList[MAX_ZOMBIES];
zombieList.PopulateZombies(zombieList[MAX_ZOMBIES]); // See the difference?
I am not sure whether the error you posted is the only error. Here is what I see in your main.cpp
#include "Gameboard.h" //for Gameboard
#include "Location.h" //for function prototypes
#include "zList.h" //for Zombies
#include <iostream> //for input/output stream
using namespace std;
void main()
{
srand(123456789);
Gameboard myGB;
myGB = Gameboard();//The constructor"Gameboard()" is automatically called when you defined
//myGB in the previous line,
ZombieListClass();//see Hai Bi's great answer on this one
ZombieRec zombieList[MAX_ZOMBIES];//ZombieRec is a member of ZombieListClass, use . to access it
PopulateZombies(zombieList[MAX_ZOMBIES]); //Also see Hai Bi's answer
}
My advice is to revisit the concept of constructor and class definition before put your hands on s a problem like this.
I am trying to create a C++ project for my Geometry class. I want the user to be able to store and access variables. To do this, I created a struct var containing string name and float value. I have a vector < var > varList in which to hold the variables. However, upon compiling, the program doesn't function well… at all. At first, it checks to see if the variable "dog" exists, which it obviously doesn't, and finds that it does. It then tries to change the variable dog and changeVar, instead of returning ERR_NONEXISTENT, returns a proper exit status of zero. Upon checking the variable, it sees that it doesn't exist. Then, when attempting to list all variables, it creates a segmentation fault. See below:
Building Generator 1.0 Alpha
Variable Systems Test
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter a variable name:
dog
Enter a value (A FLOAT!):
2.2
Checking to see if dog exists.
It exists!
Changing variable. Function returned 0
Enter a variable to check:
dog
Variable "dog" doesn't exist!
Segmentation fault
My source is here. I am compiling with Eclipse Helios, with G++ 4.2.1, on Mac 10.6.7 Snow Leopard. What's happening?
If this doesn't work, I'll try to figure out std::map…
Also, this is only my second question here; please excuse (but notify me of) any formatting mistakes.
Thanks,
BF
EDIT: Here's some code:
vsystem.cpp
/*
* vsystem.cpp
*
* Created on: Apr 29, 2011
* Author: wjc
*/
#include <string>
#include <vector>
#include <sstream>
#include "vsystem.h"
using namespace std;
vector <var> varList;
int addVar(string varName, float value){
// Check to see if varName already exists
bool varExists = false;
for (unsigned int i=0; i<varList.size(); i++){
if (varList[i].name == varName){
varExists = true;
return ERR_VAR_EXISTS;
}
}
// Good! The variable doesn't exist yet.
var tempVar;
tempVar.name = varName;
tempVar.value = value;
varList.push_back(tempVar);
return 0;
}
int changeVar(string varName, float newValue){
// Check to see if varName exists
for(unsigned int i=0; i<varList.size(); i++){
if(varList[i].name != varName){ // If it doesn't match…
if (i == varList.size() - 1) // And it's the last one…
return ERR_NONEXISTENT; // Uh oh!
} else { // Found it!
varList[i].value = newValue;
}
}
return 0;
}
fetchResult fetchVar(string varName){
fetchResult returnValue;
// Check to see if varName exists
for(unsigned int i=0; i<varList.size(); i++){
if(varList[i].name != varName){ // If it doesn't match…
if (i == varList.size() - 1){ // And it's the last one…
returnValue.good = false; // Uh oh!
returnValue.result = -1;
} else {
returnValue.good = true;
returnValue.result = varList[i].value;
}
}
}
return returnValue;
}
bool checkVar(string varName){
// Check to see if varName exists
for(unsigned int i=0; i<varList.size(); i++){
if(varList[i].name != varName){ // If it doesn't match…
if (i == varList.size() - 1) // And it's the last one…
return false; // It's not here.
}else break;
}
return true;
}
vector < var > getVarList(){
return varList;
}
string getVarList(string varDelim, string valueDelim){
stringstream final;
for (unsigned int i=0; i<varList.size()-1; i++){
final<<varList[i].name<<valueDelim<<varList[i].value<<varDelim;
// add variable name, delim 1 (probably tab), variable value, delim 2 (probably newline)
}
final<<varList.back().name<<valueDelim<<varList.back().value;
// same, but don't add a newline (or other)
return final.str();
}
vsystem.h
/*
* vsystem.h
*
* Created on: Apr 29, 2011
* Author: wjc
*/
#include <vector>
#include <string>
#include "consts.h"
using namespace std;
#ifndef VSYSTEM_H_
#define VSYSTEM_H_
struct fetchResult {
float result;
bool good;
};
struct var {
string name;
float value;
};
int addVar(string varName, float value);
int changeVar(string varName, float newValue);
fetchResult fetchVar(string varName);
bool checkVar (string varName);
vector < var > getVarList();
string getVarList(string varDelim, string valueDelim);
#endif /* VSYSTEM_H_ */
ui.h
/*
* ui.cpp
*
* Created on: Apr 26, 2011
* Author: wjc
*/
#include <iostream>
#include <vector>
#include "filedaemon.h"
#include "vsystem.h"
using namespace std;
int runUI(){
cout << " Variable Systems Test "<<endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout << endl;
cout<<"Enter a variable name:"<<endl;
string varname;
cin>>varname;
cout<<"Enter a value (A FLOAT!):"<<endl;
float value;
cin>>value;
cout<<"Checking to see if "<<varname<<" exists."<<endl;
bool alreadythere = checkVar(varname);
alreadythere ? cout<<"It exists!"<<endl : cout<<"It doesn't exist."<<endl;
if (alreadythere){
cout<<"Changing variable. Function returned "<<changeVar(varname, value)<<endl;
} else {
cout<<"Setting variable. Function returned "<<addVar(varname, value)<<endl;
}
cout<<"Enter a variable to check:"<<endl;
string varcheck;
cin>>varcheck;
fetchResult result = fetchVar(varcheck);
if(! result.good){
cout<<"Variable \""<<varcheck<<"\" doesn't exist!"<<endl;
} else {
cout<<"Variable \""<<varcheck<<"\" is equal to "<<result.result<<endl;
}
cout<<getVarList("\n","\t")<<endl;
string exitstr;
cin>>exitstr;
return 0;
}
main.cpp just calls runUI()
The way you are looping on the vector and returning true/false is weird and your app is crashing because of checkVar().
I encourage you to change all the loops on varList that search for an item to something more simple and easier to read, like:
bool checkVar(string varName)
{
// Check to see if varName exists
for (unsigned int i=0; i<varList.size(); i++)
{
if (varList[i].name == varName)
{ // If matches,
return true;
}
}
// If execution reaches here, it means it didn't found a match
return false;
}
This solves the crash. I don't know if your application has any other bugs, but this is my current output:
Building Generator 1.0 Alpha
Variable Systems Test
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter a variable name:
dog
Enter a value (A FLOAT!):
2.2
Setting variable. Function returned 0
Enter a variable to check:
alpha
Variable "alpha" doesn't exist!
dog 2.2
EDIT:
Another problem is with your defines: ERR_NONEXISTENT and ERR_VAR_EXISTS are both 1. They should have different values! I'm pasting the relevant code below:
consts.h:
#ifndef CONSTS_H_
#define CONSTS_H_
#define VERSION "1.0 Alpha"
// Variable errors
#define ERR_NONEXISTENT 0
#define ERR_VAR_EXISTS 1
// File r/w errors
#define ERR_FILE_OPEN 2
#endif /* CONSTS_H_ */
vsystem.cpp:
#include <string>
#include <vector>
#include <sstream>
#include "vsystem.h"
using namespace std;
vector <var> varList;
int addVar(string varName, float value){
// Check to see if varName already exists
bool varExists = false;
for (unsigned int i=0; i<varList.size(); i++){
if (varList[i].name == varName){
varExists = true;
return ERR_VAR_EXISTS;
}
}
// Good! The variable doesn't exist yet.
var tempVar;
tempVar.name = varName;
tempVar.value = value;
varList.push_back(tempVar);
return ERR_NONEXISTENT;
}
int changeVar(string varName, float newValue){
// Check to see if varName exists
for(unsigned int i=0; i<varList.size(); i++){
if(varList[i].name == varName)
{ // If it match, replace the value
varList[i].value = newValue;
return ERR_VAR_EXISTS;
}
}
return ERR_NONEXISTENT; // Uh oh!
}
fetchResult fetchVar(string varName){
fetchResult returnValue;
// Check to see if varName exists
for(unsigned int i=0; i<varList.size(); i++){
if(varList[i].name == varName){ // If it matches
if (i == varList.size() - 1)
{
returnValue.good = true;
returnValue.result = varList[i].value;
return returnValue;
}
}
}
returnValue.good = false; // Uh oh!
returnValue.result = -1;
return returnValue;
}
bool checkVar(string varName)
{
// Check to see if varName exists
for(unsigned int i=0; i<varList.size(); i++){
if(varList[i].name == varName)
{ // If matches, return true
return true;
}
}
// If execution reaches here, it means it didn't found a match
return false;
}
vector < var > getVarList(){
return varList;
}
string getVarList(string varDelim, string valueDelim){
stringstream final;
for (unsigned int i=0; i<varList.size()-1; i++){
final<<varList[i].name<<valueDelim<<varList[i].value<<varDelim;
// add variable name, delim 1 (probably tab), variable value, delim 2 (probably newline)
}
final<<varList.back().name<<valueDelim<<varList.back().value;
// same, but don't add a newline (or other)
return final.str();
}
I'm using visual studio 2008 to do some problems and brusg up on using c++. I have an error and I don't know why it occurs. Here's all the code. The error occurs on the line :
cout<<levels[0][0]->left->value;
with error:
error C2065: 'levels' : undeclared identifier
a shorthand of what's happening to levels is this:
//declaring it
binaryValNode*** levels;
levels = new binaryValNode** [size];
//adding arrays to the array:
for(int i = 0;i<size;i++){
levels[i] = new binaryValNode* [size];
//adding the objects
for(int k = 0; k <= i ; k++)
{
levels[i][k] = new binaryValNode();
}
//I tested cout here and it works fine
}
//but loses scope here(?)
binaryValNode is a struct with int value,binaryValNode* left and binaryValNode* right.
thanks!
code:
#include <iostream>
#include <fstream>
#include "binaryValNode.h"
using namespace std;
int main() {
int length = 0;
int size = 0;
ifstream myReadFile;
myReadFile.open("input.txt");
char* c = new char[3];
if (myReadFile.is_open()) {
while (myReadFile.getline(c,(size+1)*3)) {
size++;
c = new char[(size+1)*3];
}
binaryValNode*** levels;
levels = new binaryValNode** [size];
myReadFile.clear();
myReadFile.seekg(0);
for(int i = 0;i<size;i++){
levels[i] = new binaryValNode* [size];
c = new char[(i+1)*3];
myReadFile.getline(c,(i+1)*3);
for(int k = 0; k <= i ; k++)
{
levels[i][k] = new binaryValNode();
if(c[3*k] != '0')
{
levels[i][k]->value = ((int) c[(3*k)+1]-48) + 10*((int) c[(3*k)]-48);
}
else
{
levels[i][k]->value = (int) c[(3*k)+1]-48;
}
//
if(i!=0){
if(k==0){//only left parent
levels[i-1][k]->left = levels[i][k];
}
else if(k==i){//only right parent
levels[i-1][k-1]->right = levels[i][k];
}
else{
levels[i-1][k]->left = levels[i][k];
levels[i-1][k-1]->right = levels[i][k];
}
}
}
}
}
myReadFile.close();
cout<<levels[0][0]->left->value;
cin.get();
return 0;
}
Fix your indentation (for example, gg=G in Vim).
Right now you have
int main() {
// ...
if (myReadFile.is_open()) {
// ...
binaryValNode*** levels;
// ...
}
// ...
cout << levels[0][0]->left->value;
// ...
}
where levels is very clearly out of scope.
This needs to be moved to before the conditional:
binaryValNode*** levels;
Sort out your indentation - it will show that you have one too may closing }, and hence the problem line occurs after the end of main().
Try edit/advanced/format-selection