简体   繁体   中英

Why won't this program work?

I tried doing a simple hello world in C++ as I'm going to be using it in school in about a week. Why can't I compile this properly?

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>

Here is ram.cpp

#include <iostream>

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

EDIT:

I updated my code to

#include <iostream>
using namespace std;

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

And still get this error

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

The compiler told you why:

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

You don't use the .h . Just use

#include <iostream>

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

Per your comment, you need to buy a new book. Yours is so woefully outdated that it does not even mention namespaces! To get your program working, try this:

#include <iostream>

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

cout lives in the std namespace.

If it becomes cumbersome to type std:: often then you can import a type for the whole file like so:

using std::cout;

And now you can just write cout instead. You can also import the entire namespace, but this is generally bad practice because you are pulling the entire thing into the global namespace, and you may run into collisions down the road. However, if this is something you know will not be an issue (for example, in a throwaway app or a small utility) then you can use this line:

using namespace std;

It's not called "iostream.h", and it never was. Use #include <iostream> .

The proper code should be

#include <iostream>

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

Whatever book had been written before 2003, is not aware of this. Just throw it away. The world had moved somewhere else in the meantime!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM