I found this similar problem at
SO: error: ‘Page’ was not declared in this scope
but it is a different situation since I'm not working on header files.
As you can see from the code below, I'm using PoDoFo library trying to print out a pdf file content to the screen
#include <iostream>
#include <podofo/podofo.h>
using namespace std;
int main()
{
//load a new document
//PoDoFo::PdfMemDocument pdf("myDoc.pdf");
// this load a doc on my disk
PoDoFo::PdfMemDocument doc;
doc.Load("myDoc.pdf");
//iterate over each page"
for(int pn = 0; pn < doc.GetPageCount(); ++pn){
PoDoFo::PdfPage* page = doc.GetPage(pn);
}
//
PoDoFo::PdfContentsTokenizer tok(page);
const char* token = nullptr;
PoDoFo::PdfVariant var;
PoDoFo::EPdfContentsType type;
while (tok.ReadNext(type, token, var)) {
if (type == PoDoFo::ePdfContentsType_Keyword) {
}
}
if (var.IsArray()) {
PoDoFo::PdfArray& a = var.GetArray();
for (size_t i = 0; i < a.GetSize(); ++i)
if (a[i].IsString()) { }
}
}
This is the error:
/home/coder/QtProjects/finalProject/main.cpp:19: error: ‘page’ was not declared in this scope
PoDoFo::PdfContentsTokenizer tok(page);
hope you can help me fix this.
Thanks!
I suspect your curly braces aren't in the correct place, as per #Scheff's comment the scope of the page variable is contained within the for loop and you are attempting to do more operations after the loop is over. I moved the } for the for loop where I think it probably should be in the code below and it should work, although I also suspect the closing } of the while loop and last if might also be in the wrong spot.
#include <iostream>
#include <podofo/podofo.h>
using namespace std;
int main()
{
//load a new document
//PoDoFo::PdfMemDocument pdf("myDoc.pdf");
// this load a doc on my disk
PoDoFo::PdfMemDocument doc;
doc.Load("myDoc.pdf");
PoDoFo::PdfPage* page
//iterate over each page"
for(int pn = 0; pn < doc.GetPageCount(); ++pn){
PoDoFo::PdfPage* page = doc.GetPage(pn);
//
PoDoFo::PdfContentsTokenizer tok(page);
const char* token = nullptr;
PoDoFo::PdfVariant var;
PoDoFo::EPdfContentsType type;
while (tok.ReadNext(type, token, var)) {
if (type == PoDoFo::ePdfContentsType_Keyword) {
}
}
if (var.IsArray()) {
PoDoFo::PdfArray& a = var.GetArray();
for (size_t i = 0; i < a.GetSize(); ++i)
if (a[i].IsString()) { }
}
}
}
Related
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.
Im trying to make a object / type that consists of an element of the periodic table. But when i try to use a vector of that object as a parameter, i get this error message expected a type, got ‘Element’
here is my code so far:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
Element(int AtomicNumm, string Symboll, string Namee, double Weightt,
int Neutronss, int Protonss, string ElectronConfigg) {
string Name = Namee;
int AtomicNum = AtomicNumm;
string Symbol = Symboll;
double Weight = Weightt;
int Neutrons = Neutronss;
int Protons = Protonss;
string ElectronConfig = ElectronConfigg;
}
string returnElement(vector<Element> vec, string input) { // error here
if (input.size() == 2) {
for (int i = 0; i < vec.length(); i++) {
}
}
return "";
}
int main(int argc, char*argv[]) {
vector<Element> PT;
string userinput (argv[1]);
return -1;
}
Also, im new to c++. If objects work completely differently here please let me know. (Coming from java)
That's because you haven't declared 'Element' in your program. Syntactically, it is close to definition of a constructor.
To make your program work, i guess you can do following modification to existing element:
class Element {
// your definition of element Here:
// also include default constructor without any implementation
Element() {}
};
I have some methods in lexer.h which make use of a Vector made of Tokens.
In this method void getNextToken() I am making use of the said vector where I am adding new tokens to it.
The problem is, that when I go to a different file, I am trying to access ANOTHER method which makes use of this vector, but it is crashing with an out of bounds error (most probably it's being deferenced or something)
Is there a way how I can fix this?
The methods in concern are:
Token* nextToken()
{
if (it!= tokensUsed.end())
{
// we Assigned what is found in the iterator it (of the vector)
// so we get the data found in that pointer
itrToken = &*it;
//Move Iterator forward
it ++;
return itrToken;
}
}
/*
Used in Parser to go get the PREVIOUS Tokens
*/
Token* prevToken()
{
itrToken --;
if (it!= tokensUsed.begin())
{
itrToken = &*this->it;
return itrToken;
}
}
void getNextToken()
{
//CODE ADDING TOKENS
//EXAMPLE
if (ch == '"')
{
addAndGetNext(ch);
cout << "STRING: " << strBuffer << endl; //TEST
//create new token and push it into the vector
tk = new Token (Token::ttString, strBuffer, row, col);
tokensUsed.push_back(*tk); //Add the new token to the Vector
startNewString(); //Clear the string
}
tokenMatch = true;
}
The above is just partial code, to show an example.
Now in Parser.h I am using this method to call the lexer.h:
void relOpP()
{
Token* tk = nextToken();
if (tk -> getType() == Token::ttString)
{
cout << "Ture";
}
}
which calls the Lexer's nextToken() it crashes, and when I tried checking it's contents it goes outofBounds error (and CodeBlocks giving me a SIGSEGV error)
I know it's something from the pointers that it's going awry, but how can I fix it?
Edit:
These are the global variables I have declared:
vector<Token>::iterator it;
vector<Token> tokensUsed;
Token* itrToken; // used for iterator
bool checkQuote = false;
Token* tk = new Token (syNewToken, "", 1,0);
Token token; // Creates an instance of the class Token found in the file token.h
Token* t;
SAMPLE CODE:
main.cpp
#include <iostream>
#include "lexer.h"
#include "parser.h"
using namespace std;
int main()
{
Lexer* l;
l -> getNextToken();
Parser p(l);
p.relOpP();
}
Token (int type, string sBuffer, int rRow, int cCol)
{
this->tType = type;
this->strBuffer = sBuffer;
this->row = rRow;
this->col = cCol;
}
parser.h
#ifndef PARSER_H_INCLUDED
#define PARSER_H_INCLUDED
#include <string>
#include <vector>
#include "lexer.h"
#include "token.h"
using namespace std;
class Parser{
private:
Lexer* lexer;
string tree = "";
public:
Parser (Lexer* l)
{
this -> lexer = l;
}
Token nextToken()
{
Token tk = lexer -> nextToken();
return tk;
}
void relOpP()
{
Token tk = nextToken();
if (tk.getType() == 1)
{
cout << "Ture";
}
}
#endif // PARSER_H_INCLUDED
};
token.h
#ifndef TOKEN_H_INCLUDED
#define TOKEN_H_INCLUDED
#include <iostream>
using namespace std;
class Token
{
private:
int tType; //identifier or reserved by compiler?
string strBuffer; //string found in buffer at that moment
int row;
int col;
public:
enum tokenType
{
tkString
};
Token()
{
}
// The instance of a token with 4 parameters resulting the type, the contents of the string that represents that type
// the row it is found in and the column.
Token (int type, string sBuffer, int rRow, int cCol)
{
this->tType = type;
this->strBuffer = sBuffer;
this->row = rRow;
this->col = cCol;
}
Token (Token* getT)
{
this-> tType = getT -> tType;
this->strBuffer = getT -> strBuffer;
this->row = getT -> row;
this->col = getT -> col;
}
int getType ()
{
return this->tType;
}
//return the string contents
string getBuffer()
{
return this->strBuffer;
}
//return row
int getRow()
{
return row;
}
//return col
int getCol ()
{
return col;
}
};
#endif // TOKEN_H_INCLUDED
Lexer.h
#ifndef LEXER_H_INCLUDED
#define LEXER_H_INCLUDED
#include "token.h"
#include <vector>
using namespace std;
class Lexer
{
private:
Token tk = new Token (1, "", 1,0);
vector<Token>::iterator it;
vector<Token> tokensUsed;
Token itrToken; // used for iterator
public:
Token nextToken()
{
if (it!= tokensUsed.end())
{
// we Assigned what is found in the iterator it (of the vector)
// so we get the data found in that pointer
itrToken = &*it;
//Move Iterator forward
it ++;
return &itrToken;
}
else
{
cout << "ERROR" << endl;
}
return nullptr;
}
void getNextToken()
{
cout << "Test" << endl;
string strBuffer = "test";
int row = 0;
int col = 0;
tk = new Token (1,strBuffer,row,col);
}
};
#endif // LEXER_H_INCLUDED
In nextToken() and prevToken() there is no return for the case the if evaluates to false. The return value in that case is not very likely to be something (it could be anything...) that you can then dereference.
If you want to keep the current design you should return nullptr or (NULL if you don't have C++11 support) in that case. Then you need to change any code that uses the result of those functions to check if the pointer is valid before dereferencing it.
You would probably be better changing your design to not involve so much manual pointer manipulation. But to fix up your current version you should change your prevToken and nextToken to be something along the lines of:
Token* nextToken()
{
if (it!= tokensUsed.end())
{
...
return itrToken;
}
else
{
return nullptr;
}
}
Then if tk is the result of calling one of these functions you must not use tk-> or *tk if it is nullptr. Any code wanting to work with the result will need to check first.
So for example you could change you if statement to be:
if (tk && // Make sure tk is not nullptr
tk -> getType() == Token::ttString)
{
...
There are too many problems with your code for me to address them all in this post. The first, and most obvious one is this.
In the main function:
Lexer* l;
l -> getNextToken();
Here, you did not create a Lexer object. You just created an uninitialized pointer to one. Then you called a member function as if it pointed to an object. This is undefined behavior. You then pass this pointer to your Parser class, which continues to treat it as a valid object, resulting in more undefined behavior.
There are many other problems with your code, but most of them have to do with your mishandling of pointers, indicating a lack of understanding of how they work. The best suggestion for you is to stop using them entirely. There is no reason you need to use any pointers whatsoever to do what you are doing. If you can't figure out how to do what you are trying to do without pointers, it is because of a lack of fundamental understanding of the language. You need to read a C++ book, to completion. Here's a list of some good ones.
The Definitive C++ Book Guide and List
I am trying to create a simple stack using vector in C++.
Here is the code:
#include <vector>
class Site
{
public:
int i; // site position i (x-axis)
int s; // site state
vector<Site> neighbors;
Site(void);
Site(int ii, int ss);
void AddNeighbor(Site &site);
};
Site::Site()
{
i = -1;
s = -1;
vector<Site> neighbors;
}
Site::Site(int ii, int ss)
{
i = ii;
s = ss;
}
void Site::AddNeighbor(Site &site)
{
neighbors.push_back(site);
}
void testStack()
{
int tot = 600;
vector<Site> myStack();
int i = 0;
while (i < tot)
{
Site site(i, 1);
myStack.push_back(site);
i++;
}
i = 0;
while (i < tot)
{
Site *site = myStack.back();
myStack.pop_back();
cout << site->i << site->s << endl;
i++;
}
}
Compiler errors:
ising_wolff.cpp: In function ‘void testStack()’:
ising_wolff.cpp:373:17: error: request for member ‘push_back’ in
‘myStack’, which is of non-class type ‘std::vector()’
myStack.push_back(site);
^ ising_wolff.cpp:380:30: error: request for member ‘back’ in ‘myStack’, which is of non-class type ‘std::vector()’
Site *site = myStack.back();
^ ising_wolff.cpp:381:17: error: request for member ‘pop_back’ in ‘myStack’, which is of non-class type
‘std::vector()’
myStack.pop_back();
What do these errors mean?
Here are some sites I have looked at:
1) Creating objects while adding them into vectors
2) push_back causing errors in C
3) how to create vectors of class object
How to create a vector of class objects in C++?
Start with something simpler so you can get the hang of it.
First, create a vector of primitive ints:
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> sites(5);
sites.push_back(5);
for(int x = 0; x < sites.size(); x++){
cout << sites[x];
}
cout << endl;
return 0;
}
Compiling it:
g++ -o test test.cpp
Running it:
./test
000005
Create a vector of class objects in a similar way as above:
#include <iostream>
#include <vector>
using namespace std;
class Site {
public:
int i;
};
int main() {
vector<Site> listofsites;
Site *s1 = new Site;
s1->i = 7;
Site *s2 = new Site;
s2->i = 9;
listofsites.push_back(*s1);
listofsites.push_back(*s2);
vector<Site>::iterator it;
for (it = listofsites.begin(); it != listofsites.end(); ++it) {
cout << it->i;
}
return 0;
}
Which should print:
79
vector<Site> myStack();
This is actually a function declaration. The function is called myStack and it returns a vector<Site>. What you actually want is:
vector<Site> myStack;
The type of neighbours at the moment will store copies of the objects, not references. If you really want to store references, I recommend using a std::reference_wrapper (rather than using pointers):
vector<reference_wrapper<Site>> neighbors;
vector<Site> myStack();
This is wrong. Lose the ().
You're declaring a function, not a vector.
Just write:
vector<Site> myStack;
You could use:
vector<Site> myStack;
myStack.resize(100); //will create 100 <Site> objects
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