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

标签 c++ linux ubuntu gcc terminal

我在使用“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)时,终端返回的结果与此类似:

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不在全局命名空间中,而是在 std 中命名空间。

好吧,而不是写

using namespace std;

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

using std::cout;

因为使用第一个选项是一种不好的做法。您可以引用Why is using namespace std is a bad practice. 对于使用 using std::cout 的好处引用Using std namespace

您也可以使用std::cout如果您不想使用using std::cout,则可以到处使用.

关于c++ - 在 Ubuntu 中通过终端运行 C++ 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30693141/

相关文章:

java - 在 windows 和 linux 中转换字符集

php - PHP 和 libapache2_mod_php 有什么区别

linux - 我的 AWK 在处理最后一列时出了什么问题?

git - 如何使用 git 将更改推送到生产服务器?

security - 从不允许 scp 的服务器传输可执行文件

c++ - 第三方类型之间的隐式转换

c++ - 如何使用 CreateProcess 将输出重定向到文件?

c++ - 我应该使用哪个 *_cast 将任意整数类型的指针转​​换为 char 指针?

c++ - 混合 void_t 和可变参数模板?

找不到 php 命令