user14256058
user14256058

Reputation:

gets() is causing compilation failure with ''use of undeclared identifier 'gets'" error

I am trying to solve e problem. I am taking characters as input and using gets(). But the function is showing the above mentioned error.

I don't know why this function is misbehaving. Please help me to find the fault. I am a beginner.

As mentioned the error message is:

Use of undeclared identifier 'gets'

My C++ code:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    char line[1000];
    bool open = true;
    while (gets(line))  //***in this line gets() is showing error***
    {
        int len = strlen(line);
        for (int i = 0; i < len; i++)
        {
            if (line[i] == '"')
            {
                if (open)
                {
                    printf("``");
                }
                else
                {
                    printf("''");
                }
                open = !open;
            }
            else
            {
                printf("%c", line[i]);
            }
        }
        printf("\n");
    }

    return 0;
}

enter image description here

Upvotes: 1

Views: 3771

Answers (2)

anastaciu
anastaciu

Reputation: 23802

std::gets was deprecated in C++11 and removed from C++14, this a dangerous function and it should never be used, though some compilers still provide it, it looks like it's not your case, which is a good thing.

You should use something like std::getline, note that for this you'll need the line argument to be std::string.

string line;

//...

while (getline(cin, line)){
    //...
}

Alternatively, if you really need a char array, you can use fgets instead:

char line[1000];
//...
while(fgets(line, sizeof line, stdin)){
   //remove newline character using strcspn
   line[strcspn(line, "\n")] = '\0';
   //or with C++ std::replace
   replace(&line[0], &line[1000], '\n', '\0'); //&line[1000] one past the array end
   //...
}

Side note:

Consider not using using namespace std; and #include <bits/stdc++.h>, follow the links for details.

Upvotes: 2

pcodex
pcodex

Reputation: 1940

gets() is deprecated as already mentioned. Read about it here

But let's get to the root cause of why you got the error in the first place. An

undeclared identifier 'gets'

error is because the compiler can't find the declaration of the function you are using. In your case gets() is defined in stdio.h

I also see that you're using std::getline() as recommended and for that you need to include the string header.

Take a look at the 2 links I've mentioned to understand proper usage.

Upvotes: 0

Related Questions