26

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:

 #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.

My compiler says the error is this

error: strlen was not declared in this scope

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
Person
  • 903
  • 3
  • 11
  • 12

4 Answers4

55

You forgot to include <cstring> or <string.h>.

cstring will give you strlen in the std namespace, while string.h will keep it in the global namespace.

Rapptz
  • 20,807
  • 5
  • 72
  • 86
11

You need to include cstring header for 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.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
0

You can include <cstring>, then you won't get any errors.

code

#include<iostream>
#include<cstring>
 using namespace std;

 int main()
 {
    char buffer[80];

    cout << "Enter a string:";
    cin >> buffer;
    cout << strlen(buffer);

    return 0;

 }

-1

You can use string.h header file in C++ but it is generally not recommended. In C++, the string class is part of the standard library and provides more functionality for manipulating strings than the functions declared in string.h.

The string class provides features like dynamic memory allocation, overloaded operators, iterators, and more, making it easier to work with strings in C++. Using string.h in C++ may limit the benefits of these features and make the code harder to read and maintain.

To use the string class in C++, you can include the header file. This header file declares the std::string class and associated functions and provides a more modern and efficient way of working with strings in C++.