字符串长度:static_cast无效

时间:2016-05-15 08:33:19

标签: c++11 casting static type-conversion

我期待这个sample code能够正常工作:

std::string s;
int number=1;
s = std::to_string(number);
int size=static_cast<int>(s.length);

然而它给出了错误:

main.cpp:178:39:错误:从类型''到'int'类型的static_cast无效      int size = static_cast(s.length);

然后,我也tried

int size=atoi(s.length);

这给了我错误:

 cannot convert ‘std::basic_string<_CharT, _Traits, _Alloc>::length<char, std::char_traits<char> 
... to type ‘const char*’

然后,我尝试了这个option

int size=atoi(s.c_str());

这个有效。任何提示为什么atoi(s.length)不起作用,而不是atoi(s.c_str())是必需的?

因此,假设我输入字符串为999,数字总数为3.使用s.length将是获得总数的最佳方法,但s.length cast会给出错误。< / p>

1 个答案:

答案 0 :(得分:2)

您没有调用char *str[] = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" } 方法。 您应该使用length:注意int size=static_cast<int>(s.length());方法名称末尾的调用运算符。

但是,如果这样做,你试图将字符串转换为整数,这是错误的。这只会给你字符串中的字符数。