功能类似于 Strlen C++
我想创建一个与 Strlen 相同的函数,但收到错误:“字符串下标超出范围”。我尝试修复它但不知道。
这是代码:
#include "stdafx.h"
#include "stdafx.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int strlen1( string str)
{
int count=0;
int i=0;
while (str[i]!='\0')
{
count++;
i++;
}
return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
string input;
cin >> input;
cout << strlen1(input) << endl;
return 0;
}
谢谢!
I want to make a function that will do the same as Strlen does, andI get the error: "string subscript out of range". I tried fixing it but has no idea.
heres the code:
#include "stdafx.h"
#include "stdafx.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int strlen1( string str)
{
int count=0;
int i=0;
while (str[i]!='\0')
{
count++;
i++;
}
return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
string input;
cin >> input;
cout << strlen1(input) << endl;
return 0;
}
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简而言之,对于非
const
std::string
访问超出字符串长度的元素具有未定义的行为(更准确地说,当使用非const< /code>
operator[]
)。C++98 §21.3.4/1,关于
std::string::operator[]
:并且您的字符串是非 const 的。
您可以将其设置为 const,这将调用标准中的一个特殊规定,保证元素 n 的结果为零,但这并不能解决您的函数完全不可用的问题对于
std::string
来说是多余的。也许您的意思是使用参数类型
char const*
。这会更有意义,然后该功能也会起作用。
干杯&呵呵,,
In short, for a non-
const
std::string
accessing an element beyond the string length has Undefined Behavior (more precisely, when using the non-const
operator[]
for that).C++98 §21.3.4/1, about
std::string::operator[]
:And your string is non-
const
.You can make it
const
, which will then invoke a special provision in the standard that guarantees zero result for element n, but that does not address the problem that your function is completely redundant forstd::string
.Perhaps you mean to have argument type
char const*
.That would make more sense, and then also the function would work.
Cheers & hth.,
您似乎误解了 std::string 与 C 样式字符串 (char const*) 相同。这根本不是真的。没有空终止符。
这是 strlen 函数的唯一工作方式:
You seem to be under the misconception that std::string is the same as a C-style string (char const*). This is simply not true. There is no null terminator.
Here's your strlen function the only way it will work:
std::string
有一个很好的size()
方法。std::string
has a nicesize()
method for this.strlen 基于零终止字符串(char* 或 char 数组),C++ 字符串基于长度+数据,您无法访问字符串末尾(终端零所在的位置)之后的数据。除此之外,获取长度是 C++ 字符串的标准属性 (size()),因此编写 strlen 的标准方法就是调用 size。
strlen is based on zero terminated strings (char*, or char arrays), C++ string are based on length + data, you can't access to data after the end of string (where a terminal zero would be). Beside that, getting the length is a standard property of C++ strings (size()), hence the standard way of writing strlen is just to call size.