strcpy was not declared in this scope?

Dawry Jones picture Dawry Jones · Jul 14, 2015 · Viewed 12.8k times · Source
#include <iostream>
#include <string>
using namespace std;

int main()
{
    char Buffer[20] = {'\0'};

    cout << "Enter a line of text: " << endl;
    string LineEntered;
    getline (cin, LineEntered);

    if ( LineEntered.length() < 20 ){
        strcpy(Buffer, LineEntered.c_str()); // This strcpy. is not declared in scope for some reason.
        cout << "Buffer contains: " << Buffer << endl;
    }

    return 0;
}

This is the error:

main.cpp:14:43: error: 'strcpy' was not declared in this scope

Why is it having this error?

Answer

Greg Hewgill picture Greg Hewgill · Jul 15, 2015

The strcpy function is in the include file string.h. So add:

#include <string.h>

Or, alternatively if you want to be more C++ about it,

#include <cstring>

and use std::strcpy().