在 Ubuntu 中通过终端遇到问题 运行 C++

Trouble running C++ through terminal in Ubuntu

我使用"gedit take_input.cpp"后写了如下代码:

#include <iostream>

int main() 
{
cout<<"please enter your name (followed by 'enter')\n";

string file;

cin >> file;

cout<<"hello" << file << " ! welcome to ilinux, where innovation is a promise\n";
}

然而,当我使用 "g++" 将我的人类可读代码转换为目标代码(写 g++ take_input.cpp -o take_input)时,终端 returns 的结果类似于:

take_input.cpp: In function ‘int main()’:
take_input.cpp:5:1: error: ‘cout’ was not declared in this scope
 cout<<"please enter your name (followed by 'enter')\n";
 ^
take_input.cpp:5:1: note: suggested alternative:
In file included from take_input.cpp:1:0:
/usr/include/c++/4.9/iostream:61:18: note:   ‘std::cout’
   extern ostream cout;  /// Linked to standard output
                  ^
take_input.cpp:7:1: error: ‘string’ was not declared in this scope
 string file;
 ^
take_input.cpp:7:1: note: suggested alternative:
In file included from /usr/include/c++/4.9/iosfwd:39:0,
                 from /usr/include/c++/4.9/ios:38,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from take_input.cpp:1:
/usr/include/c++/4.9/bits/stringfwd.h:62:33: note:   ‘std::string’
   typedef basic_string<char>    string;   
                                 ^
take_input.cpp:9:1: error: ‘cin’ was not declared in this scope
 cin >> file;
 ^            ^
take_input.cpp:9:8: error: ‘file’ was not declared in this scope
 cin >> file;
take_input.cpp:9:1: note: suggested alternative:
In file included from take_input.cpp:1:0:
/usr/include/c++/4.9/iostream:60:18: note:   ‘std::cin’
   extern istream cin;  /// Linked to standard input
                  ^
take_input.cpp:9:8: error: ‘file’ was not declared in this scope
 cin >> file;
        ^

能告诉我是什么原因吗?

只需阅读编译器给您的错误消息即可。问题是

‘cout’ was not declared in this scope

而 "suggested alternative" 是 std::coutstringstd::string.

也是如此

注意,一般来说,属于标准库的东西需要用std::限定才能找到。

您还需要 #include <string> 才能使用 std::string 顺便说一句。

只需添加

using namespace std;

#include <iostream>

之后

试试这个。

编译器在第 7 行给出了答案:因为您没有使用 std 命名空间,所以您必须在 cout 和 [=13= 之前添加 std:: ] 来电。

您收到的错误是因为 cout 不在全局命名空间中,而是在 std 命名空间中。

嗯而不是写

using namespace std;

#include <iostream> 之后尝试使用:

using std::cout;

因为使用第一个选项是一种不好的做法。可以参考Why is using namespace std is a bad practice. 有关使用 using std::cout 的好处,请参阅 Using std namespace

如果你不想使用 using std::cout,你也可以在任何地方使用 std::cout