Shivam Haldiya
Shivam Haldiya

Reputation: 1

Multiple `cin` is not giving correct answer

Entering the value in cin directly with 1212121221121212 + 34343434343434 = 1246464655464646 gives no solution. Why?

#include <iostream>
using namespace std;

int main() {
    long int a, b, c;
    char op, eq;
    cout << "Input the formula: ";
    cin >> a >> op >> b >>eq >> c;
    long int sum;
    if (op == '+') {
        sum = a + b;
    }
    else {
        sum = a - b;
    }
    
    if (sum == c) {
        cout << "Correct";
    }
    else {
        cout << "No Solution";
    }
    return 0;
}

Upvotes: 0

Views: 73

Answers (1)

user4581301
user4581301

Reputation: 33982

Other than lacking a check for bad user input the logic looks sound. After adding a simple check for bad input

if (std::cin >> a >> op >> b >> eq >> c) // testing for valid input
{
    ...
}
else
{
    std::cout << "bad input. Buh-bye!"; // inform user of bad input
}

User input of 1212121221121212 + 34343434343434 = 1246464655464646 results in output of bad input. Buh-bye!

The most probably cause of the bad input is the numbers given exceeding the maximum capacity of a 32 bit integer (the common interpretation of long int on most desktop computers). Increasing the capacity of the numbers to at least 64 bits with int_least64_t seems to resolve the issue, at least for now.

#include <iostream>
#include <cstdint> // needed for int_least64_t

int main()
{
    int_least64_t a, b, c; // guaranteed larger type
    char op, eq;
    std::cout << "Input the formula: ";
    if (std::cin >> a >> op >> b >> eq >> c) // testing for valid input
    {
        int_least64_t sum; // guaranteed larger type
        if (op == '+')
        {
            sum = a + b;
        }
        else
        {
            sum = a - b;
        }

        if (sum == c)
        {
            std::cout << "Correct";
        }
        else
        {
            std::cout << "No Solution";
        }
    }
    else
    {
        std::cout << "bad input. Buh-bye!"; // inform user of bad input
    }
    return 0;
}

The problem will return when numbers once again get too large to fit in a int_least64_t. If you have to support such numbers, look into using an arbitrary length integer library.

Upvotes: 1

Related Questions