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

2019-07-24 09:05发布

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

标签: c++ c gets
5条回答
做个烂人
2楼-- · 2019-07-24 09:13

C functions are subset of c++ functions, but no, you probably don't want gets() in c++ project.

You may consider getline() or operator>> for stream. Did they not tell you anything about it in the university?

查看更多
虎瘦雄心在
3楼-- · 2019-07-24 09:17

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.

查看更多
ら.Afraid
4楼-- · 2019-07-24 09:25

gets is a c function

You are probably looking for istream/ostream/fstream and so on.

See for example: http://www.cplusplus.com/reference/iostream/istream/read/

查看更多
你好瞎i
5楼-- · 2019-07-24 09:28

gets is a c function , First link on google for gets . You should probably look at functions in iostream , fstream etc

查看更多
孤傲高冷的网名
6楼-- · 2019-07-24 09:34

This example won't compile because the header for the gets is cstdlib and its a c function.

查看更多
登录 后发表回答