需求:将file1中的每行的每个单词保存在string容器中
BUG : 每行的最后一个单词不打印
origin code:
int main()
{
ifstream input_file;
vector<string> ivec;
string s, s_word;
input_file.open(FILE_NAME, ifstream::in);
string::const_iterator itor_s;
while(!input_file.eof())
{
getline(input_file, s);
itor_s = s.begin();
s_word.clear();
for(itor_s;itor_s != s.end(); itor_s++)
{
if(*itor_s != ' ')
{
s_word.push_back(*itor_s);
if(itor_s == s.end() ) { ivec.push_back(s_word); s_word.clear(); }
}
else if((*itor_s == ' '))
{
if(!s_word.empty()) { ivec.push_back(s_word); s_word.clear(); }
}
else {continue;}
}
//ivec.push_back(s);
}
vector<string>::const_iterator itor = ivec.begin();
for(itor;itor != ivec.end(); itor ++)
{
cout << *itor << endl;
}
return 0;
}
准备GDB调试:
int main()
{
ifstream input_file;
vector<string> ivec;
string s, s_word;
input_file.open(FILE_NAME, ifstream::in);
string::const_iterator itor_s;
while(!input_file.eof())
{
getline(input_file, s);
itor_s = s.begin();
s_word.clear();
for(itor_s;itor_s != s.end(); itor_s++)
{
if(*itor_s != ' ')
{
s_word.push_back(*itor_s);
if(itor_s == s.end() ) { ivec.push_back(s_word); s_word.clear(); }
}
else if((*itor_s == ' '))
{
if(!s_word.empty()) { ivec.push_back(s_word); s_word.clear(); }
}
else {continue;}
}
//ivec.push_back(s);
}
vector<string>::const_iterator itor = ivec.begin();
for(itor;itor != ivec.end(); itor ++)
{
cout << *itor << endl;
}
return 0;
}
复习GDB:
- 编译文件必须加上 -g 选项,不然会报错:no debugging symbols found
gcc -g xxx.cpp -o xxx
如果没有-g,你将看不见程序的函数名、变量名,所代替的全是运行时的内存地址。
- 常用GDB命令:
l (小写的L) :list 显示源代码
break 123 :设置123行断点
break func1 : 设置func1函数入口断点
into break : 查看断点信息
r :run,运行程序,停留在断点
n:单步执行
c:continue继续运行
p i : 打印参数i
bt:查看函数堆栈情况
finish:退出函数
q:退出gdb调试
最最常用的:help -- 查看所有选项帮助
有一篇介绍GDB比较完整的文档
单步调试发现,
if(itor_s == s.end() ) { ivec.push_back(s_word); s_word.clear(); }
这句话永远没有执行
(gdb) p s.end()
发现,这个是文件结束符‘\0’, 这就是关键所在!!!因为for循环取得 *itor_s 最大是走到字串最后一个有效字符
解决方案:
for(itor_s;itor_s != s.end(); itor_s++) 改成
for(itor_s;itor_s != s.end() -1; itor_s++)
打印出来成功,
BUG FIXED