Counting digits using while loop

前端 未结 7 601
清酒与你
清酒与你 2021-01-05 10:15

I was recently making a program which needed to check the number of digits in a number inputted by the user. As a result I made the following code:

int x;            


        
7条回答
  •  难免孤独
    2021-01-05 10:41

    You could read the user input as a string, and then count the characters? (After sanitising and trimming, etc.)

    Alternatively, you could get a library to do the hard work for you; convert the value back to a string, and then count the characters:

    cin >> x;
    stringstream ss;
    ss << x;
    int len = ss.str().length();
    

提交回复
热议问题