Include iostream c что это ошибка

В visual studio C++, при создании нового проекта, вместо #include <iostream> (как в примерах) стоит #include <stdafx.h>.
Если его заменить на #include <iostream>, то получается ошибка компиляции.

Можно это как-то изменить?

Vladimir Gamalyan's user avatar

задан 23 дек 2017 в 10:36

Skilef's user avatar

4

Это особенность Visual Studio, которая может ускорять сборку проекта. Начинающих только сбивает с толку. Рекомендую её просто отключить, только и всего. Тогда все будет работать как по учебнику.

Для этого зайдите в свойства проекта (правая кнопка по проекту в solution explorer, properties) и в Precompiled Headers отключите их как показано на рисунке:

введите сюда описание изображения

ответ дан 23 дек 2017 в 16:18

Vladimir Gamalyan's user avatar

Vladimir GamalyanVladimir Gamalyan

7,7235 золотых знаков27 серебряных знаков57 бронзовых знаков

4

Visual Studio использует #include <stdafx.h> для реализации предкомпилированных заголовков — то есть, для ускорения компиляции. #include <stdafx.h> должно быть первой существенной строкой файла (то есть, непустой и не комментарием).

Если вам нужно указать #include <iostream>, укажите его следующей строкой.


Я бы не рекомендовал отказываться от #include <stdafx.h> и предкомпилированных заголовков. Правильное использование предкомпилированных заголовков улучшает время компиляции, особенно в больших проектах.

ответ дан 23 дек 2017 в 11:03

VladD's user avatar

VladDVladD

206k27 золотых знаков290 серебряных знаков521 бронзовый знак

1

ПростоЯ

184 / 101 / 8

Регистрация: 30.05.2009

Сообщений: 782

1

23.02.2010, 20:39. Показов 33728. Ответов 10

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Почему при добавлении строчки

C++
1
#include <iostream.h>

выдает ошибку
fatal error C1083: Cannot open include file: ‘iostream.h’: No such file or directory



0



Sergei

1509 / 776 / 103

Регистрация: 22.04.2008

Сообщений: 1,610

23.02.2010, 20:40

2

Пишите так

C++
1
2
#include <iostream>
using namespace std;



3



184 / 101 / 8

Регистрация: 30.05.2009

Сообщений: 782

23.02.2010, 20:41

 [ТС]

3

Спасибо. Заработало.



0



3 / 3 / 1

Регистрация: 11.10.2009

Сообщений: 52

23.02.2010, 20:48

4

эм.. а подскажите товарищи, для каких функций используется iostream ?



0



Эксперт JavaЭксперт С++

8381 / 3613 / 419

Регистрация: 03.07.2009

Сообщений: 10,708

23.02.2010, 21:07

5

Suslik73, используется для консольных потоков ввода/вывода языка С++ и их модификаторов



1



Maniac

Эксперт С++

1463 / 964 / 160

Регистрация: 02.01.2009

Сообщений: 2,818

Записей в блоге: 1

23.02.2010, 21:24

6

Цитата
Сообщение от Suslik73
Посмотреть сообщение

эм.. а подскажите товарищи, для каких функций используется iostream ?

IOstream Library



1



ниначмуроФ

851 / 535 / 110

Регистрация: 12.10.2009

Сообщений: 1,913

24.02.2010, 00:28

7

а почиму у меня #include <iostream> не работает а
#include <iostream.h> работает. От чего зависит?



0



║XLR8║

1212 / 909 / 270

Регистрация: 25.07.2009

Сообщений: 4,361

Записей в блоге: 5

24.02.2010, 00:29

8

PointsEqual, от компилятора, у тебя поддержка старого стандарта



1



Эксперт С++

7175 / 3234 / 81

Регистрация: 17.06.2009

Сообщений: 14,164

24.02.2010, 20:44

9

а почиму у меня #include <iostream> не работает а
#include <iostream.h> работает. От чего зависит?

Выкини свой Visual Studio 6.0



0



ниначмуроФ

851 / 535 / 110

Регистрация: 12.10.2009

Сообщений: 1,913

25.02.2010, 08:27

10

у меня его нет)



0



Эксперт CАвтор FAQ

21265 / 8281 / 637

Регистрация: 30.03.2009

Сообщений: 22,646

Записей в блоге: 30

25.02.2010, 10:03

11

Цитата
Сообщение от PointsEqual
Посмотреть сообщение

а почиму у меня #include <iostream> не работает а
#include <iostream.h> работает. От чего зависит?

У тебя старый компилятор. Вариант с фалами iostream.h — это старые стандарты. В новых убрали расширение .h



0



  • Forum
  • Beginners
  • Error with #include <iostream>

Error with #include <iostream>

I’m having problems with this code —

1
2
3
4
5
6
7
8
// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}

I keep getting this error —

1
2
3
4
5
6
7
mingw32-gcc.exe    -c C:UsersDuckkTVDesktopHelloWorldHelloWorld.c -o C:UsersDuckkTVDesktopHelloWorldHelloWorld.o
C:UsersDuckkTVDesktopHelloWorldHelloWorld.c:2:20: iostream: No such file or directory
C:UsersDuckkTVDesktopHelloWorldHelloWorld.c: In function `main':
C:UsersDuckkTVDesktopHelloWorldHelloWorld.c:4: error: syntax error before ':' token
Process terminated with status 1 (0 minutes, 0 seconds)
2 errors, 0 warnings (0 minutes, 0 seconds)
  

Please help!

Last edited on

1 Error is you just have «return» on line 7. That needs to be «return 0;»

That was a copy and paste error :) fixed the «return 0;» on line 7
Still having problems with the #include <iostream>

1
2
3
4
5
6
7
8
9
10
#include "stdafx.h"
#include <iostream>

using namespace std;

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

Give that a try. I was having the same error and this fixed it.

if you want to show hello world, you need to use only one ‘cout’.
#include<iostream.h>
int main()
{
cout<<«Hello world»<<endl;
return 0;
}

If #include <iostream.h> works you should think about updating your compiler.
@powerbg We weren’t talking about he cannot see the results. He cannot compile it. Also use Code tags.

The stdafx thingy shouldn’t be your case, as your project is on your desktop, and stdafx is a VS’s thing who by default puts your projects in the Documents folder.

Also try renaming your files from .c to .cpp

Last edited on

Still no luck :( What do you use to code/ writing program? I am currently using codeblocks. But I don»t know all my ways around it. Right now what i do is

Could that the the problem ?

@EssGeEich
How do i rename it to CPP in CodeBlocks ?

Last edited on

You should remove the file from the project, rename it manually, and re-add the file to the project.

try right clicking on the file and selecting «rename» from the context menu.

IT WORKED !!!!!!
Thanks man!

@Disch There is no Rename in C::B
@DuckkTV You’re Welcome

EDIT: I must be blind, I just noticed there is a Rename File.

Last edited on

oh lol

were is the renmame button ?

Okay thanks!

Topic archived. No new replies allowed.

I learn C++ and COM through the books.
In the IDE MS Visual Studio 2012 I have created new empty C++ project, and added some existing files to it. My CPP file contains #include<iostream> row, but in editor I got such messages:

Error: identifier «cout» is undefined

end

Error: identifier «endl» is undefined

Code:

#include<iostream>
#include"interfaces.h" // unknown.h, objbase.h, initguid.h

class CA {//: public IX, IY{
public:
    // Constructor
    CA();
    // Destructor
    ~CA();
    // IUnknown
    virtual HRESULT __stdcall QueryInterface(const IID& iid, void** ppv);
    virtual ULONG __stdcall AddRef();
    virtual ULONG __stdcall Release();
    // IX
    virtual void __stdcall Fx1();
    virtual void __stdcall Fx2();
    // IY
    virtual void __stdcall Fy1(){ cout << "Fy1" << endl; }  // errors here
    virtual void __stdcall Fy2(){ cout << "Fy2" << endl; }  // errors here also
private:
    long counter;
};

Why it happens?

JaMiT's user avatar

JaMiT

14k4 gold badges15 silver badges31 bronze badges

asked Nov 3, 2012 at 11:03

Andrey Bushman's user avatar

Andrey BushmanAndrey Bushman

11.6k17 gold badges85 silver badges180 bronze badges

2

You need to specify the std:: namespace:

std::cout << .... << std::endl;;

Alternatively, you can use a using directive:

using std::cout;
using std::endl;

cout << .... << endl;

I should add that you should avoid these using directives in headers, since code including these will also have the symbols brought into the global namespace. Restrict using directives to small scopes, for example

#include <iostream>

inline void foo()
{
  using std::cout;
  using std::endl;
  cout << "Hello world" << endl;
}

Here, the using directive only applies to the scope of foo().

answered Nov 3, 2012 at 11:04

juanchopanza's user avatar

juanchopanzajuanchopanza

222k33 gold badges399 silver badges479 bronze badges

1

You can add this at the beginning after #include <iostream>:

using namespace std;

Tom Fenech's user avatar

Tom Fenech

71.9k12 gold badges106 silver badges139 bronze badges

answered Feb 25, 2014 at 16:03

arash's user avatar

cout is in std namespace, you shall use std::cout in your code.
And you shall not add using namespace std; in your header file, it’s bad to mix your code with std namespace, especially don’t add it in header file.

answered Nov 3, 2012 at 11:04

billz's user avatar

billzbillz

44.4k9 gold badges83 silver badges100 bronze badges

1

The problem is the std namespace you are missing. cout is in the std namespace.
Add using namespace std; after the #include

answered Aug 21, 2020 at 16:17

Abdellah Ramadan's user avatar

If you have included #include iostream and using namespace std; it should work. If it still doesn’t work, make sure to check that you haven’t deleted anything in the iostream file. To get to you iostream file, just Ctrl +Click your #include iostream and it should take you to that file. You can paste the below original iostream file to your iostream file and it should work.

// Standard iostream objects -*- C++ -*-

// Copyright (C) 1997-2019 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.

// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://www.gnu.org/licenses/>.

/** @file include/iostream
 *  This is a Standard C++ Library header.
 */

//
// ISO C++ 14882: 27.3  Standard iostream objects
//

#ifndef _GLIBCXX_IOSTREAM
#define _GLIBCXX_IOSTREAM 1

#pragma GCC system_header

#include <bits/c++config.h>
#include <ostream>
#include <istream>

namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION

  /**
   *  @name Standard Stream Objects
   *
   *  The &lt;iostream&gt; header declares the eight <em>standard stream
   *  objects</em>.  For other declarations, see
   *  http://gcc.gnu.org/onlinedocs/libstdc++/manual/io.html
   *  and the @link iosfwd I/O forward declarations @endlink
   *
   *  They are required by default to cooperate with the global C
   *  library's @c FILE streams, and to be available during program
   *  startup and termination. For more information, see the section of the
   *  manual linked to above.
  */
  //@{
  extern istream cin;       /// Linked to standard input
  extern ostream cout;      /// Linked to standard output
  extern ostream cerr;      /// Linked to standard error (unbuffered)
  extern ostream clog;      /// Linked to standard error (buffered)

#ifdef _GLIBCXX_USE_WCHAR_T
  extern wistream wcin;     /// Linked to standard input
  extern wostream wcout;    /// Linked to standard output
  extern wostream wcerr;    /// Linked to standard error (unbuffered)
  extern wostream wclog;    /// Linked to standard error (buffered)
#endif
  //@}

  // For construction of filebuffers for cout, cin, cerr, clog et. al.
  static ios_base::Init __ioinit;

_GLIBCXX_END_NAMESPACE_VERSION
} // namespace

#endif /* _GLIBCXX_IOSTREAM */

answered Oct 31, 2021 at 13:30

Yaakov Brill's user avatar

You Check your C++ version or You must write this statement to global scope
using namespace std;

answered May 16 at 7:23

Ganesh Pawar's user avatar

1

you have to use:using namespace std
or else
you have to write using std::endl ie import only endl from std library.

answered Feb 5 at 14:01

Naveen Kamath's user avatar

1

  

Facing compilation errors can be frustrating, especially when the error messages are not very helpful. In this guide, we will discuss how to resolve the `fatal error: iostream: No such file or directory` error that occurs while compiling C++ programs.

## Table of Contents

1. [Understanding the Error](#understanding-the-error)
2. [Step-by-Step Solution](#step-by-step-solution)
3. [FAQs](#faqs)
4. [Related Links](#related-links)

## Understanding the Error

This error occurs when the compiler is unable to locate the iostream header file, which is a crucial part of the C++ Standard Library. It provides functionality for input and output operations, such as reading from the keyboard and displaying text on the screen. The most common reasons for this error are:

- Incorrectly including the header file
- Using an outdated or misconfigured compiler

## Step-by-Step Solution

### Step 1: Verify the Header File Inclusion

Make sure you have included the iostream header file correctly in your source code. The correct syntax is:

```cpp
#include <iostream>

If you have used a different syntax, like #include "iostream", change it to the correct one and recompile your code.

Step 2: Check the Compiler Installation

If the error still persists, check if your compiler is installed correctly. You can do this by running the following command in your terminal or command prompt:

g++ --version

If you get an error or the version number is lower than 5.1, consider updating your compiler.

Step 3: Verify the Compiler’s Include Path

The compiler needs to know where to find the header files. You can check the default include path by running the following command:

g++ -E -x c++ - -v < /dev/null

Look for the «include» directory in the output. If it does not contain the path to the iostream header file, you may need to reinstall your compiler or update the include path manually.

Step 4: Update the Include Path Manually (Optional)

If you have determined that the include path is the problem, you can update it manually by adding the -I option followed by the path to the iostream header file when compiling your code. For example:

g++ -I/path/to/your/include/directory your_source_file.cpp -o your_output_file

FAQs

The iostream header file is a part of the C++ Standard Library that provides functionality for input and output operations, such as reading from the keyboard and displaying text on the screen.

2. Why am I getting the «fatal error: iostream: No such file or directory» error?

This error occurs when the compiler is unable to locate the iostream header file, which can be due to an incorrect inclusion, an outdated or misconfigured compiler, or an incorrect include path.

3. How can I check if my compiler is installed correctly?

You can check if your compiler is installed correctly by running the following command in your terminal or command prompt:

g++ --version

4. How can I update my compiler?

You can update your compiler by following the official installation guide.

5. Is it possible to manually update the include path?

Yes, you can update the include path manually by adding the -I option followed by the path to the iostream header file when compiling your code.

  • GCC Installation Guide
  • C++ Standard Library Reference
  • Common C++ Compilation Errors
    «`

Понравилась статья? Поделить с друзьями:
  • In most western nations advanced general найти ошибки
  • In function int main int char ошибка
  • Ims service что это ошибка
  • Ims service выдает ошибку что делать
  • Impulserc driver fixer ошибка 99