2012-03-22 78 views
0

我试过在C++中做一个简单的Hello World,因为我将在大约一个星期内在学校使用它。为什么我不能正确编译它?为什么这个程序不能工作?

c:\Users\user\Desktop>cl ram.cpp 
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86 
Copyright (C) Microsoft Corporation. All rights reserved. 

ram.cpp 
ram.cpp(1) : fatal error C1083: Cannot open include file: 'iostream.h': No such 
file or directory 

c:\Users\user\Desktop> 

这里是ram.cpp

#include <iostream> 

int main() 
{ 
    cout << "Hello World!"; 
    return 0; 
} 

编辑:

我更新了我的代码

#include <iostream> 
using namespace std; 

int main(void) 
{ 
    cout << "Hello World!"; 
    return 0; 
} 

,仍然可以得到这个错误

ram.cpp 
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\xlocale(323) : wa 
rning C4530: C++ exception handler used, but unwind semantics are not enabled. S 
pecify /EHsc 
Microsoft (R) Incremental Linker Version 10.00.30319.01 
Copyright (C) Microsoft Corporation. All rights reserved. 

/out:ram.exe 
ram.obj 
+2

不会向我们展示'ram.cpp'吗? – asawyer 2012-03-22 21:57:56

+0

对不起,我将它添加到 – netbyte 2012-03-22 22:18:13

+0

你是否正在从一个正常的命令提示符或Visual Studio命令提示符运行此设置所有环境变量设置? – tinman 2012-03-22 22:41:49

回答

9

编译器告诉你为什么:

ram.cpp(1):致命错误C1083:无法打开包含文件: 'iostream.h':没有这样的 文件或目录

你不不要使用.h。只需使用

#include <iostream> 

A long winded explanation with a lot of background can be found here.

根据您的意见,您需要购买一本新书。你的过时太糟糕了,甚至没有提到命名空间!为了让你的程序工作,试试这个:

#include <iostream> 

int main() 
{ 
    std::cout << "Hello World!"; 
    return 0; 
} 

cout生活在std命名空间。

如果它成为累赘键入std::的时候则可以导入类型整个文件像这样:

using std::cout; 

现在你可以只写cout代替。您也可以导入整个名称空间,但这通常是不好的做法,因为您将整个事件拖入全局名称空间,并且您可能会遇到碰撞事故。但是,如果这是你知道会不会是一个问题的东西(例如,在一个一次性的应用程序或小程序),那么你可以使用此行:

using namespace std; 
+0

感谢您的链接解释 – antlersoft 2012-03-22 22:02:27

+0

谢谢。但现在我得到这个错误 c:\ Users \ alex \ Desktop> cl ram。cpp Microsoft(R)32位C/C++优化编译器版本16.00.30319.01,用于80x86 版权所有(C)Microsoft Corporation。版权所有。 ram.cpp C:\ Program Files文件(x86)\ Microsoft Visual Studio 10.0 \ VC \ INCLUDE \ xlocale(323):wa rning C4530:使用C++异常处理程序,但unwind语义未启用。 S pecify/EHsc ram.cpp(4):错误C4430:缺少类型说明符 - int假定。注意:C++不支持default-int ram.cpp(5):错误C2065:'cout':未声明的标识符 – netbyte 2012-03-22 22:11:43

+1

@netbyte:'cout'在命名空间'std'中。你正在阅读的是什么书,它向你展示了旧的标题和非命名空间符号,将它放下。烧了吧。 [获取更好的书](http://stackoverflow.com/q/388242/636019)。 – ildjarn 2012-03-22 22:18:32

5

它不叫“iostream.h”,并它从来没有。使用#include <iostream>

+3

在ISO之前,很多旧书都使用这些标题。 – ildjarn 2012-03-22 22:00:46

1

正确的代码应该是

无论本书在2003年之前已经写
#include <iostream> 

int main() 
{ 
    std::cout << "Hello World!" << std::endl; 
    return 0; 
} 

,是没有意识到这一点。 只要把它扔掉。在此期间,世界已经搬到了别的地方!

+0

你怎么能不用每次都记住std呢? – netbyte 2012-03-22 23:01:40

+0

@netbyte:'std'是一个名字空间,你不要“叫”它。请参考我对埃德关于获得一本真实书籍的回答的评论。 ; - ] – ildjarn 2012-03-23 00:32:35

相关问题