如何在c ++中找到整数的长度? [关闭]

问题描述 投票:-7回答:1

我试图使用以下方法对每个数字进行分区,但在某些情况下不起作用。例如,数字00123应该返回长度5作为输出而不是3是否有解决方案?

#include<stdio.h>
void main()
{

int n,count=0;
scanf("%d",&n);
while(n!=0)
{
 n/=10;
 ++count;
}
printf("%d",count);
}
c++ arrays
1个回答
1
投票

您不能将“00123”存储为int - 因为前导零将被忽略。所以,为了保存,你必须存储为string

std::string my_int_str = "00123";

然后打印长度是微不足道的:

std::cout << my_int_str.length();
© www.soinside.com 2019 - 2024. All rights reserved.