Search code examples
c++stringcompiler-errorscin

Why is g++ Giving Me Conflicting Errors While Compiling?


I am attempting to compile my second, (still noobish) C++ program, and g++ is giving me these errors:

new.cpp: In function ‘int main()’:
new.cpp:10:4: error: ‘cin’ was not declared in this scope
    cin >> name;

is the first. Here's the second:

    ^~~
new.cpp:10:4: note: suggested alternative:
In file included from new.cpp:1:
/usr/include/c++/8/iostream:60:18: note:   ‘std::cin’
   extern istream cin;  /// Linked to standard input
                  ^~~

and I believe these are telling me to change both ways to write it to the other. I have tried changing both, and I'm not sure how to fix this. Here is the program:

#include <iostream>
#include <string>

int main() {
 std::string age;
 std::string name;
    std::cout << "Please input your age.";
   std::cin >> age;
    std::cout << "Please input your name.";
   cin >> name;
    return 0;
}

(CLOSED)


Solution

  • Here is a little bit of explanation for a c++ and g++ newbie:

    new.cpp:10:4: error: ‘cin’ was not declared in this scope

    cin is declared under the std namespace. See https://en.cppreference.com/w/cpp/io/cin

    The second one is not an error, but a suggestion by the compiler by pointing to the alternative found by the compiler. It gives a hint about std::cin.

    note: suggested alternative:
    In file included from new.cpp:1:
    /usr/include/c++/8/iostream:60:18: note:   ‘std::cin’
       extern istream cin;  /// Linked to standard input
                      ^~~
    

    At line 10, you are using cin from the global namespace. Therefore, the compiler complains that it can't find the declaration of cin.

    Our fellow already provided a fix for you by changing line 10 to: std::cin >> name;.

    #include <iostream>
    #include <string>
    
    int main() {
        std::string age;
        std::string name;
        std::cout << "Please input your age.";
        std::cin >> age;
        std::cout << "Please input your name.";
        std::cin >> name;
        return 0;
    }