How to read multiple expressions from a file?

I have the following code

int main()
{
    Expression* expression;
    char paren, comma;
    string program;

    freopen("input", "r", stdin);

    while (true)
    {
        cout << "Enter expression: ";
        cin >> paren;
        expression = SubExpression::parse();
        cin >> comma;  
        parseAssignments();
        cout << "Value = " << expression->evaluate() << endl;
        if(cin.eof())
            break;
    }

    return 0;
}

void parseAssignments()
{
    char assignop, delimiter;
    string variable;
    int value;
    do
    {
        variable = parseName();
        cin >> ws >> assignop >> value >> delimiter;
        symbolTable.insert(variable, value);
    }
    while (delimiter == ',');
}

I want to read multiple expressions from a file using cin only. No matter where I put cin.eof() in the while loop, program reads input one more time and then crashes. I ahve also tried cin.peek() but still the same output. Suggest a ways to read EOF.

Answers


As has been discussed countless times before, eof() is never the right tool.

You want this:

Expression * expression = nullptr;

for (char paren, comma;
     std::cin >> paren                     &&
     (expression = SubExpression::parse()) &&
     std::cin >> comma                     &&
     parseAssignments();
    )
{
    std::cout << "Value: " << expression->evaluate() << "\n";
}

Here we assume that both parse() and parseAssignments() return something that's convertible to true on success and false on failure (like a null pointer).

You might also want to insert checks that the delimiters are as expected, e.g. paren == '(' and comma == ','.


Need Your Help

how to ignore backing up certain tables with innobackupex

percona

I am using innobackupex to back up my database but I need to ignore a few tables.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.