为什么 g++ 在编译时给我冲突的错误?

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

我正在尝试编译我的第二个(仍然是菜鸟)C++ 程序,但 g++ 给我这些错误:

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

是第一个。这是第二个:

    ^~~
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
                  ^~~

而且我相信这些是在告诉我改变这两种方式以将其写入另一种方式。我试过改变两者,但我不确定如何解决这个问题。这是程序:

#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;
}

(关闭)

以下是对c++和g++新手的一点解释:

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

cinstd 命名空间下声明。参见 https://en.cppreference.com/w/cpp/io/cin

第二个不是错误,而是编译器的建议,指向编译器找到的替代方案。它给出了关于 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
                  ^~~

在第 10 行,您正在使用来自全局命名空间的 cin。因此,编译器报错找不到 cin.

的声明

我们的同事已经通过将第 10 行更改为: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;
}