Search code examples
c++cgets

Is gets() considered a C function or a C++ function?


#include <iostream>
using namespace std;

void main(){
    char name[20];
    gets(name);
    cout<<name<<endl;
}

I can't found answer in google, function gets() is C or C++ language function ? Because in university I must use only C++ functions.


Solution

  • gets() is a C function dating to the 1960's, it does not do bounds checking and is considered dangerous, is has been kept all this years for compatibility and nothing else.

    Your code in valid and recommended C++ should be:

    #include <iostream>
    using namespace std;
    
    int main(){
        // C style NULL terminated string NOT the same as a C++ string datatype 
        //char name[20];
        string name;// C++ string datatype, meant to use with C++ functions and features
        cin >> name;
        cout<<name<<endl;
        return 0;
    }
    

    You should avoid to mix C specific features with C++ features as the string datatype/object. There are ways to use both, but as beginner you should stick to one or the other.

    My personal recomendation, do C first, adn then transition to C++. Most C++ programmers are bad at pure C, the C language came first, and was used as the foundation environment for C++, but both have grown apart with time in more ways that you can imagine.

    So unless you are studying object orientation simultaneosly with C++, all you will do is code in C with a C++ compiler. C++ is also very large in comparison to C. Templates and Object Oriented Programming facilities being the reasons to use C++ in the first place.

    Pure C is still great for many things, is small and elegant. Its easier to get proficient at C than C++. C++ has grown to much to be manageable without sticking to a subset of features agreed by any developer team.