24

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
  • 269,602
  • 39
  • 394
  • 697
Person
  • 843
  • 3
  • 10
  • 12

3 Answers3

51

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,187
  • 4
  • 71
  • 86
10

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
  • 148,593
  • 36
  • 425
  • 712
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;

 }