c++ string类length()(size())函数返回值–无符号数
首先,先来发现问题
string s = "";
for(int i = 0; i < s.length() - 1; ++i)
{
cout << "s.length = " <<s.length() << endl;
break;
}
- 1
- 2
- 3
- 4
- 5
- 6
输出结果:
s.length = 0
显然,这句话不该输出。通过查看QT编译器下面的警告发现,
string类的length()或者size()函数返回的是unsigned integer(无符号数)类型。而用在for循环时,正常不会出错,但作为判断条件时,当s.length()等于0时,s.length()-1 不等于 -1
例2
string s = "";
for(int i = 0; i < s.length() - 1; ++i)
{
cout << "s.length - 1 = " << s.length()-1 << endl;
break;
}
- 1
- 2
- 4
输出结果:
s.length()-1 = 4294967295
例3
可以将例2中代码改为如下,强制类型转换一下。
string s = "";
for(int i = 0; i < (int)s.length() - 1; ++i)
{
cout << "(int)s.length - 1 = " << s.length()-1 << endl;
break;
}
#include <cstring> #include <iostream> using namespace std; int main(){ string a, b, c; cin >> a >> b; for(int i = 0; i <= (int)a.length()/2 - 1; i++) swap(a[i], a[a.length() - i - 1]); // int lenb = b.length(); for(int i = 0; i <= (int)b.length()/2 - 1; i++){ //string类的length()或者size()函数返回的是 //unsigned integer(无符号数)类型。而用在for循环时, //正常不会出错,但作为判断条件时, //当s.length()等于0时,s.length()-1 不等于 -1 swap(b[i], b[b.length() - i - 1]); // cout << b.length() / 2 - 1 << endl; } if(a.length() > b.length()) b.append(a.length() - b.length(), '0'); else a.append(b.length() - a.length(), '0'); char str[13] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'J', 'Q', 'K'}; for(int i = 0; i < a.length(); i++){ cout << "i: " << i << endl; if(i % 2 == 0){ c += str[(b[i] - '0' + a[i] - '0') % 13]; } else{ int k = b[i] - a[i]; if(k < 0) k += 10; c += str[k]; } } for(int i = c.length() - 1; i >= 0; i--) cout << c[i]; return 0; }
- 1
- 2
- 3
- 4
- 5
- 6
输出结果:
(int)s.length - 1 = -1
总结:string类的length()函数和size()函数一定要注意返回的是无符号数,当出现string对象length为0,对于string对象的操作更要注意,以防出错