Error: C++ requires a type specifier for all declarations
Asked Answered
S

3

6

I'm new to C++ and I've been reading this book. I read a few chapters and I thought of my own idea. I tried compiling the code below and I got the following error:

||=== Build: Debug in Password (compiler: GNU GCC Compiler) ===| /Users/Administrator/Desktop/AppCreations/C++/Password/Password/main.cpp|5|error: C++ requires a type specifier for all declarations| ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 2 second(s)) ===|.

I don't understand what is wrong about the code, might anyone explain what's wrong and how to fix it? I read the other posts but I was unable to understand it.

Thanks.

#include <iostream>

using namespace std;

main()
{
    string password;
    cin >> password;
    if (password == "Lieutenant") {
        cout << "Correct!" << endl;
    } else {
        cout << "Wrong!" << endl;
    }

}
Sihon answered 27/1, 2015 at 3:32 Comment(2)
You also need a #include <string>.Comfrey
@Sihon Please do not edit your question to include the answer. It makes it confusing for people who haven't read the question yet. Instead, click the "tick" mark next to one of the posted answers to show that you accept that answer.Steinbok
B
7

You need to include the string library, you also need to provide a return type for your main function and your implementation may require you to declare an explicit return statement for main (some implementations add an implicit one if you don't explicitly provide one); like so:

#include <iostream>
#include <string> //this is the line of code you are missing

using namespace std;

int main()//you also need to provide a return type for your main function
{
    string password;
    cin >> password;
    if (password == "Lieutenant") {
        cout << "Correct!" << endl;
    } else {
        cout << "Wrong!" << endl;
    }
return 0;//potentially optional return statement
}
Benedetta answered 27/1, 2015 at 3:37 Comment(0)
G
5

You need to declare the return type for main. This should always be int in legal C++. The last line of your main, in many cases, will be return 0; - i.e. exit successfully. Anything other than 0 is used to indicate an error condition.

Gamali answered 27/1, 2015 at 3:37 Comment(1)
return 0 is always implicit for main.Celebrate
F
4

One Extra Point:

You can also get exact same error if you try to assign variable in class. Because in C++ you can initialize variables in class but can't assign later after variable declaration but if you try to assign in a function which is defined in the class then it would work perfectly fine in C++.

Fanelli answered 26/5, 2021 at 7:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.