本文仅作记录调试中碰到的一个小问题。
string str = "";
对于上述定义,在调戏代码时发现一个str在调试时鼠标悬浮的信息str "",而对该变量进行正常的判空时会失败。后来调用了str.size()函数发现str的长度为1,颇为费解。
后来通过调用win32的API OutPutDebugString将str的内容打印到调试器中才发现字符串的实际内容。模拟的测试代码如下:
#include "iostream"
#include "windows.h"
using namespace std;
int main()
{
string str = "";
if (str.empty())
{
cout << "str is empty." << endl;
}
str = "\n";
if (str.compare("\n") == 0)
{
cout << "str is " << "\\n." << endl;
}
OutputDebugString("**********\n");
OutputDebugString(str.c_str());
OutputDebugString("\n");
OutputDebugString("**********\n");
system("pause");
return 0;
}
简单分析一下,string自带的empty()判断的是str.size() == 0,因此当str.size() != 0的时候,str.empty()的返回值必然为false。因为工作环境面对的不是控制台程序,所以打印信息用到了windows的OutputDebugString(),而上述代码打印的结果如下:
很显然,多了一个回车即"\n",这时才恍然大悟去监视中查看str的内容发现str两次赋值的内容分别如下:
str[0] = 10恰好对应ASCII表中的换行符。
看来以后调试的时候不能偷懒啊,只看悬浮提示的信息可能会错过很多信息。