Stuti
Stuti

Reputation: 67

to_string().length() giving incorrect results in c++. Can anyone please explain me this behavior?

#include <iostream>
using namespace std;

int main()
{
    int n,t;
    cin>>n;

    for(int i=0;i<n;i++)
    {
        cin>>t;
        cout<<to_string(t).length();
    }
    return 0;
}

Test Cases:
Input-123 //Correct
Output-3

Intput-111111111111111111111111 //Incorrect
Output-10

Input-11111 //Incorrect
Output-1010

Upvotes: 2

Views: 401

Answers (1)

Nathaniel Blanquel
Nathaniel Blanquel

Reputation: 162

This is most likely caused by cin reading as much of an int as it can when you assign 111111111111111111111111 to t, note that 111111111111111111111111 goes beyond the capacity size for int, it even goes beyond the capacity of long long int. Then as for fixing your output, chain an endl statement to the end of your output statement as so:

cout << to_string(t).length() << endl;

If you insist on making your code work for integers that exceed capacity then you might want to check out some arithmetic libraries such as the GMP Arithmetic Library

Upvotes: 2

Related Questions