我在使用“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/