将字符串转换为int

时间:2018-09-04 20:45:30

标签: c++

我想检查Pesel号(字符串e)是否为11位数字,问题是转换为int后,temp在调试语句中显示随机值。

示例:

e = 74090927433
temp = 1076483401。

e = 81111638872
temp = -492739752

代码:

void setPesel(string e)
{
    cout <<"Correct value:"<<e<<endl;
    int digits=0;
    std::string copied = e;
    int temp = atoi(copied.c_str());
    cout <<"Wrong value:"<<temp<<endl;
    while(temp != 0)
    {
        temp = temp/10;

        digits++;
    }
    if (digits !=11)
    {
        pesel="Nie prawidlowy numer pesel";
    }
    else

        pesel=e;
}

3 个答案:

答案 0 :(得分:0)

无论您使用哪种变体,c ++中的整数都不能包含10个以上的数字。您可以在那里看到不同类型的范围:What range of values can integer types store in C++

对于您所描述的问题,您似乎必须确保使用long long int。尽管如果只希望输入的长度,您甚至可以直接在字符串上检查它,那就更好了!

答案 1 :(得分:0)

您的平台上的int似乎无法保持该值(通常为32位,很可能您的平台也不例外)。最简单的解决方案是避免将数字的字符串表示形式转换为二进制值-您已经以十进制格式表示它,因此只需使用std::string::length()std::string::size()。如果您需要验证/规范化,只需删除前导零和/或算术符号,那应该比将如此大的数字转换为二进制格式更简单:

void setPesel(string e)
{
     if ( e.length() != 11 )
        pesel="Nie prawidlowy numer pesel";
    else
        pesel=e;
}

或一个班轮:

void setPesel(string e)
{
     pesel = ( e.length() != 11 ? std::string("Nie prawidlowy numer pesel") : e );
}

答案 2 :(得分:0)

您不需要将字符串转换为整数,然后使用%运算符。
可以使用std::isdigit

const size_t length = e.length();
bool all_digits = true;
for (size_t i = 0; i < length; ++i)
{
  if (!std::isdigit(e[i]))
  {
     all_digits = false;
     break;
  }
}
if (all_digits && (length == 11))
{
  std::cout << "Number has all digits and 11 total.\n";
}
else
{
  std::cout << "Test is either not a number or less than 11 digits.\n";
}