Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can not compile C++ constructor

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();

        }
like image 265
user1325414 Avatar asked Jul 29 '26 17:07

user1325414


2 Answers

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

like image 160
Seth Carnegie Avatar answered Aug 01 '26 07:08

Seth Carnegie


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

like image 39
tigrang Avatar answered Aug 01 '26 08:08

tigrang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!