/*
* 最近在读取文件的时候用到了c++里面的seekg(fstream::off_type, fstream::seekdir),
* 很自然的调用seekg(-str.size(), fstream::cur);结果悲剧了,文件指针却向前移动很多个
* 字节。纠结了半天,改调用为seekg(-(int)str.size(), fstream::cur),指针移动正常。
* 可是为什么会这样呢??想必读者也会困惑吧!这里面其实跟c语言的自动类型转换有关。
* 首先,借用一个网上一道面试题:
* ***********************************************************************************
* unsigned int a = 4;
* int b = -20;
* if(a + b > 4)
* cout << "a + b > 4";
* else cout << "a + b <= 4";
* 结果输出为:a + b > 4
* 解释就是:无符号与有符号参加运算时,有符号类型会自动转换为无符号类型。也就是说b与a
* 做加法时,b自动转换为无符号类型,就是一个非常大的正数。结果a+b当然也是个很大的正数。
* ***********************************************************************************
* 回到我们的问题,seekg(-str.size(),fstream::cur)中,str.size()返回类型是
* string::size_type,其实就是unsigned int类型。当与-1做乘法时,-1就被临时转化为unsigned
* int类型,十六进制表示就是0xffff,结果就相当于(0xffff)*str.size(),这个结果当然是个很
* 大的正数。所以在函数调用之后,文件指针向前移动了很多个字节。
*
* 另外再做一下说明:
* long long test1 = -str.size();
* int test2 = -str.size();
* test1 和 test2 结果是不一样的,test2返回的逻辑上正确的负数,
* test1 返回的是大正数,自己根据补码想一想就知道了。
*
* 附上测试代码......
*/
#include <iostream>
#include <fstream>
#include <bitset>
#include <string>
using namespace std;
int main()
{
unsigned int a = 4;
int b = -20;
cout << "binary(a) = " << bitset<32>(a) << endl;
cout << "binary(b) = " << bitset<32>(b) << endl;
if(a + b > 4)
{
cout << "a + b = " << a + b << " #a+b>4" << endl;
}
else cout << "a + b = " << a + b << "#a+b<4" << endl;
bitset<32> bs(a + b);
cout << "binary(a + b) = "<< bs << endl;
int test1 = a + b;
cout << "test1 = " << test1 << endl;
bitset<32> bs2(test1);
cout << "binary(test1) = " << bs2 << endl;
long long test2 = a + b;
cout << "test2 = " << test2 << endl;
bitset<64> bs3(test2);
cout << "binary(test2) = " << bs3 << endl;
return 0;
}
#include <fstream>
#include <bitset>
#include <string>
using namespace std;
int main()
{
unsigned int a = 4;
int b = -20;
cout << "binary(a) = " << bitset<32>(a) << endl;
cout << "binary(b) = " << bitset<32>(b) << endl;
if(a + b > 4)
{
cout << "a + b = " << a + b << " #a+b>4" << endl;
}
else cout << "a + b = " << a + b << "#a+b<4" << endl;
bitset<32> bs(a + b);
cout << "binary(a + b) = "<< bs << endl;
int test1 = a + b;
cout << "test1 = " << test1 << endl;
bitset<32> bs2(test1);
cout << "binary(test1) = " << bs2 << endl;
long long test2 = a + b;
cout << "test2 = " << test2 << endl;
bitset<64> bs3(test2);
cout << "binary(test2) = " << bs3 << endl;
return 0;
}
本文出自 “东方快翔” 博客,请务必保留此出处http://hustluy.blog.51cto.com/1792080/1031222