string类出现out of range 求帮助,如何改正

hackairM 2013-08-15 12:07:01
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
void toup(string &str);
int main()
{
string str;
getline(cin,str);
while(str!="q")
{
toup(str);
cout<<str<<endl;
cout<<"Next string (q to quit):\n";
getline(cin,str);
}
system("pause");
return 0;
}
void toup(string &str)
{
cout<<str.size()<<"lenght.....";
int i=0;
while(str[i])
{
if(islower(str[i]))
str[i]=toupper(str[i]);
i++;
}
}
程序编译无错误,执行的时候,输入str后会出现out of range错误,求指导问题出在哪里?应该如何改正?
...全文
927 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
zj2012zy 2013-08-15
  • 打赏
  • 举报
回复
string 类型不以‘\0'结尾,所以会一直循环,直到越界
ztenv 版主 2013-08-15
  • 打赏
  • 举报
回复
像这种问题,debug一下就能找到了,见一楼吧
max_min_ 2013-08-15
  • 打赏
  • 举报
回复
越界引起的

out of range

大尾巴猫 2013-08-15
  • 打赏
  • 举报
回复
Toup函数中: while(str[i]) 循环有问题,会越界 string并不保存字符串最后的'\0' 应该用for循环 for(int i = 0; i < str.size(); i++) ....
大尾巴猫 2013-08-15
  • 打赏
  • 举报
回复
引用 5 楼 u010335328 的回复:
[quote=引用 1 楼 ananluowei 的回复:] Toup函数中: while(str[i]) 循环有问题,会越界 string并不保存字符串最后的'\0' 应该用for循环 for(int i = 0; i < str.size(); i++) ....
string是以'\0'结尾吗?如果是,为什么不行?如果不是,那是以什么结尾?[/quote] string不是'\0'结尾的,没有结尾,string内部有1个表示长度的变量来控制字符数组的大小。 str.size()就得到这个表示长度的变量。 string内部是字符数组,不是以'\0'结尾的字符串。
hackairM 2013-08-15
  • 打赏
  • 举报
回复
引用 1 楼 ananluowei 的回复:
Toup函数中: while(str[i]) 循环有问题,会越界 string并不保存字符串最后的'\0' 应该用for循环 for(int i = 0; i < str.size(); i++) ....
string是以'\0'结尾吗?如果是,为什么不行?如果不是,那是以什么结尾?

64,639

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧