C++ 使用 strlen() 时“未在此范围内声明”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17626619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'not declared in this scope' when using strlen()
提问by Person
I am trying to compile this piece of code but for whatever reason it won't work. Can someone help me? I want to know how to use strlen() properly:
我正在尝试编译这段代码,但无论出于何种原因它都行不通。有人能帮我吗?我想知道如何正确使用 strlen() :
#include<iostream>
using namespace std;
int main()
{
char buffer[80];
cout << "Enter a string:";
cin >> buffer;
cout << strlen(buffer);
return 0;
}
I've tried using cin.getline(buffer, 80); but I get the same compile error issue.
我试过使用 cin.getline(buffer, 80); 但我遇到了同样的编译错误问题。
My compiler says the error is this
我的编译器说错误是这样的
error: strlen was not declared in this scope
错误:strlen 未在此范围内声明
回答by Rapptz
You forgot to include <cstring>
or <string.h>
.
您忘记包含<cstring>
或<string.h>
。
cstring
will give you strlen
in the std
namespace, while string.h
will keep it in the global namespace.
cstring
会给你strlen
在std
命名空间中,同时string.h
将它保留在全局命名空间中。
回答by Shafik Yaghmour
You need to include cstring
header for strlen
:
您需要包含cstring
标题strlen
:
#include <cstring>
you could alternatively include string.h
and that would put strlen
in the global namespace as opposed to std
namespace. I think it is better practice to use cstring
and to drop using using namespace std
.
您也可以包含string.h
并且将放入strlen
全局命名空间而不是std
命名空间。我认为使用cstring
和放弃使用using namespace std
.