Bug大全(不定时更新ing)

来源:互联网 发布:nginx rtmp 直播人数 编辑:程序博客网 时间:2024/04/29 02:21

1、

string path ( "D:\\xxxxx.txt" ); ifstream inf;    inf.open(path);    if(!inf)    {        cout<<" open failed! "<<endl;        abort();    //打开失败,结束程序    }

执行以上程序后报错,屏幕显示“open failed !”

原因:

1)路径名错误/找不到该文件。注意文件路径一定要到“ .txt ”等后缀为止才是完整的;注意路径名中要用双斜杠“\”或是反斜杠“/”。
2)访问权限问题。文件存在于桌面文件等有访问限制的文件夹中无法读取,因此最好将文件放在普通文件夹中
3)open方法传入的数据类型错误,官方文档声明如下:

std::ifstream::open(const char* filename,                     ios_base::openmode mode = ios_base::in);

修正:

方法一:直接将string声明为const型

const string path( "D:\\xxxxx.txt" );

方法二:用const_cast将path修改为const char*型

inf.open( const_cast<char*>(path.c_str()) );//c_str()将string 转成char*//const_cast将变量转换为const类型

方法三:

CString path( _T("D:\\xxxxx.txt") );//关于cstring的头文件,在vs中://cstringt.h/afx.h          MFC-only string objects//atlstr.h                  Non-MFC string objects

2、
vector中的erase()函数要小心!
尤其在for循环中使用可能会出现数组越界!

vector<int> a = { 1, 2, 3, 4 };    for (auto i = a.begin(); i != a.end(); i++){        if (*i % 2 == 0)            auto it = a.erase(i);  //此时不管用不用it来接收结果,it和i都同时指向被删除的下一个元素位置!    }

最好这样写:

vector<int> a = { 1, 2, 3, 4 };    for (int i = 0; i < a.size(); i++){        if (a[i] % 2 == 0){            a.erase(a.begin() + i);        }    }

注意: 如果是要和前一个元素比较的,要注意这样写:

vector<int> a = { 1, 2, 2, 2, 3 };    for (int i = 1; i < a.size(); i++){        if (a[i] == a[i - 1]){            a.erase(a.begin() + i);            i--;    //注意这个!因为此时少了一个元素了!        }    }
0 0
原创粉丝点击