简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM