在Ubuntu中通过终端运行C ++时出现问题

时间:2015-06-07 11:46:38

标签: 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";
}

然而,当我使用&#34; g ++&#34;要将我的人类可读代码转换为目标代码(编写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;
        ^

你能告诉我原因是什么吗?

4 个答案:

答案 0 :(得分:3)

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

  

'cout'未在此范围内声明

“建议的替代方案”是std::coutstringstd::string相同。

请注意,通常,属于标准库的内容需要通过std::进行限定才能找到。

您还需要#include <string>才能使用std::string btw。

答案 1 :(得分:3)

您获得的错误是因为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

答案 2 :(得分:0)

编译器在第7行给出答案:由于您未使用std命名空间,因此必须在std::cout个调用之前添加cin

答案 3 :(得分:-2)

添加

using namespace std;
#include <iostream>

之后

试试这个。