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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:18:21  来源:igfitidea点击:

'not declared in this scope' when using strlen()

c++

提问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>

cstringwill give you strlenin the stdnamespace, while string.hwill keep it in the global namespace.

cstring会给你strlenstd命名空间中,同时string.h将它保留在全局命名空间中。

回答by Shafik Yaghmour

You need to include cstringheader for strlen:

您需要包含cstring标题strlen

 #include <cstring>

you could alternatively include string.hand that would put strlenin the global namespace as opposed to stdnamespace. I think it is better practice to use cstringand to drop using using namespace std.

您也可以包含string.h并且将放入strlen全局命名空间而不是std命名空间。我认为使用cstring和放弃使用using namespace std.