Sunday, October 30, 2022

[FIXED] How to determine if a line from a input file is the last line? c++

Issue

I have written a program to check for balanced curly brackets in a .cpp file. The program works fine and finds the syntax error, displays the number of the line with the problem and then exits.

But I have to display a different error message if the error is at the last line of the input cpp file.

I have tried to implement it like following way but I think it is wrong. It doesn't work anyway :)

else
                {
                    if(current == inputFile.eof()) //THIS IS WHAT I TRIED
                    {
                        cout << "Syntax error at the end of the program.";
                    }
                    else
                    {
                        cout << "Syntax error in line: " << current << "\n";
                        errorFound == true;
                    }
                }

I did not give the complete code because I think a simple if condition with the correct variable will solve this. If you need it, I can post the code later.

EDIT: Larger piece of the code is given as requested. counter is an int variable that is updated every line by counter++.

for(int i = 0; i < line.length(); i++)
        {
            if (line[i] == '{')
            {
                stack.push(current);
            }
            else if(line[i] == '}')
            {
                if (!stack.isEmpty())
                {
                    stack.pop(opening);
                    cout << "Code block: " << opening << " - " << current << "\n";
                }
                else
                {
                    if(current == inputFile.eof())
                    {
                        cout << "Syntax error at the end of the program.";
                    }
                    else
                    {
                        cout << "Syntax error in line: " << current << "\n";
                        errorFound == true;
                    }
                }
            }

Solution

This is the best solution I could think of. There is probably a better one.

std::ifstream input_file{ "file.txt };
std::vector<std::string> contents;

// fill vector with file contents
std::string cline;
while (std::getline(input_file, cline))
    contents.push_back(cline);

// now loop
for (const auto& line : contents) {
    //...
    if (&line == &contents.back()) {
        // do something at the end of file
    }
}

You can use an iterator version if you don't like the pointer comparison :)



Answered By - Rakete1111
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.