Can anyone please explain to me whats wrong with this piece of code and how to fix it? this is part of a bigger project if you need more information in order to give an anwer please let me know.
the error that im getting is this:
g++ -c search.cpp
search.cpp: In constructor ‘Search::Search()’:
search.cpp:26:26: error: ‘callnumber’ was not declared in this scope
make: *** [search.o] Error 1
Search::Search()
{
ifstream input;
input.open("data.txt", ios::in);
if(!input.good())
//return 1;
string callnumber;
string title;
string subject;
string author;
string description;
string publisher;
string city;
string year;
string series;
string notes;
while(! getline(input, callnumber, '|').eof())
{
getline(input, title, '|');
getline(input, subject, '|');
getline(input, author, '|');
getline(input, description, '|');
getline(input, publisher, '|');
getline(input, city, '|');
getline(input, year, '|');
getline(input, series, '|');
getline(input, notes, '|');
Book *book = new Book(callnumber, title, subject, author, description, publisher, city, year, series, notes);
Add(book);
}
input.close();
}
On this line:
if(!input.good())
//return 1;
string callnumber;
You commented out the line with the semicolon and you're not using braces, and C++ is not white-space sensitive when it comes to spaces and newlines1 between tokens, so by taking out the comment (and adding indentation) we can see that it's the equivalent of
if (!input.good())
string callnumber;
And we can see that the declaration of callnumber is local to the if. Add braces or a semicolon to make the declaration of callnumber be outside the if (or just remove it completely):
if (!input.good()) { // or ;
//return 1;
}
string callnumber;
1 Except in macros
Because you've commented this line
if(!input.good())
//return 1;
The string callnumber is only declared inside that scope and unusable outside of it.
Remove the if statement too or uncomment the return line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With