如果访问错误的字符串索引,c ++不会引发错误 [英] c++ does not throw error if accessing wrong index of string

查看:35
本文介绍了如果访问错误的字符串索引,c ++不会引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

string s = "haha";
cout << s << endl; //haha
cout << s.length() << endl; //4
cout << (s[25] == 'h' ? "is h" : "is not h") << endl; //is not h
cout << s[0] << endl; // h
cout << s[25] << endl; // nothing...blank

似乎指向任何索引,即使索引超出范围也不会引发任何错误……原因是什么?

It seems that pointing to any index even if it is out of range does not throw any error...what is the reason?

推荐答案

效率.您可以使用 at 函数进行边界检查.

Efficiency. You can use at function for bounds check.

这篇关于如果访问错误的字符串索引,c ++不会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆