Как подключить iostream в visual studio
I am new to c++. I just started! I tried a code on visual c++ 2010 Express version but i got the following code error message.
This is the code
FYI, you should avoid using tabs in your code. They are very difficult to deal with when formatting on Q&A sites like this. Use spaces instead.
I assume your include path includes the VC include directory (under program files). However, when installing VC did you select the native files?
Hi david, this is what i have in my include path : Program files (x86) > Microsoft Visual Studio 10.0 > VC > include > srv.h
14 Answers 14
@sparkyShorts so when we usually code in C/C++ the usual standard that is to be followed is to not write "using namespace XXX" to avoid confusion when someone is debugging the code. Instead, we directly use the namespace name and call its library function. e.g. std::cout, std::cin, std::vector, etc.
Using *.h for any header file is only recommended for external libraries to that of standard C++, so if you are including a standard C/C++ library, please avoid using ".h" as a suffix.
Exposing the whole namespace and on top of that for including a standard header sounds like a broken mess. I would check the other answers.
Some things that you should check:
Check the include folder in your version of VS (in " C:\Program Files\Microsoft Visual Studio xx.x\VC\include " check for the file which you are including, iostream , make sure it's there).
Check your projects Include Directories in > Properties > Configuration Properties > VC++ Directories > Include Directories - (it should look like this: $(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include; )
Make sure that you selected the correct project for this code ( File > New > Project > Visual C++ > Win32 Console Application )
Make sure that you don't have anywhere in your code files, VS doesn't support that (in the same project, check your other code files, .cpp and .h files for and remove it).
Make sure that you don't have more than one main() function in your project code files (in the same project, check your other code files, .cpp and .h files for the main() function and remove it or replace it with another name).
Some things you could try building with:
- Exclude using namespace std; from your main() function and put it after the include directive.
- Use std::cout without using namespace std; .
@ Secko : what do i check in these lines: Check the include folder in your version of VS. Check you projects Include Directories in
The above worked for me. The below did not:
This also failed:
You are more than likely missing $(IncludePath) within Properties->VC++ Directories->Include Directories. Adding this should make iostream and others visible again. You probably deleted it by mistake while setting up your program.
It is possible that your compiler and the resources installed around it were somehow incomplete. I recommend re-installing your compiler: it should work after that.
i have tried a number of times. Same outcome. I am considering using a different compiler. Please can you suggest anyone?
I got this error when I created an 'Empty' console application in Visual Studio 2015. I re-created the application, leaving the 'Empty' box unchecked, it added all of the necessary libraries.
If your include directories are referenced correctly in the VC++ project property sheet -> Configuration Properties -> VC++ directories->Include directories.The path is referenced in the macro $(VC_IncludePath) In my VS 2015 this evaluates to : "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include"
That did it for me.
Объявляет объекты, управляющие чтением из стандартных потоков и записью в них. Это часто является единственным заголовком, который требуется выполнить в программе C++ для ввода и вывода.
Синтаксис
Комментарии
Объекты можно разделить на две группы:
cin , cout , cerr и clog являются байт-ориентированными, выполняя обычные передачи байтов за раз.
wcin , , wcout wcerr и wclog являются широкими ориентированными, переводя на широкие символы, которые программа управляет внутренне.
После выполнения определенных операций в потоке, таких как стандартные входные данные, нельзя выполнять операции другой ориентации в одном потоке. Таким образом, программа не может работать взаимозаменяемо и cin wcin , например.
Все объекты, объявленные в этом заголовке, имеют своеобразное свойство— можно предположить, что они созданы до определения статических объектов в блоке перевода. Кроме того, можно предположить, что эти объекты не уничтожаются перед деструкторами для любых таких статических объектов, которые вы определяете. (Однако выходные потоки сбрасываются во время завершения программы.) Таким образом, вы можете безопасно считывать данные из стандартных потоков до запуска программы и после завершения программы.
Однако эта гарантия не является универсальной. Статический конструктор может вызвать функцию в другой записи преобразования. Вызываемая функция не может предположить, что объекты, объявленные в этом заголовке, были построены, учитывая неопределенный порядок, в котором единицы перевода участвуют в статической конструкции. Чтобы использовать эти объекты в таком контексте, необходимо сначала создать объект класса ios_base::Init .
Глобальные объекты потоков
Имя | Описание |
---|---|
cerr | Указывает глобальный поток cerr . |
cin | Указывает глобальный поток cin . |
clog | Указывает глобальный поток clog . |
cout | Указывает глобальный поток cout . |
wcerr | Указывает глобальный поток wcerr . |
wcin | Указывает глобальный поток wcin . |
wclog | Указывает глобальный поток wclog . |
wcout | Указывает глобальный поток wcout . |
Объект cerr управляет выходными данными в буфер потока, связанный с объектом stderr , объявленным в .
Возвращаемое значение
Комментарии
Этот объект управляет вставкой без буферизации в стандартный вывод ошибок в виде байтового потока. После создания объекта выражение cerr.flags & unitbuf ненулевое и cerr.tie() == &cout . Дополнительные сведения см. здесь: cerr.flags и unitbuf .
Например, .
Указывает глобальный поток cin .
Возвращаемое значение
Комментарии
Объект контролирует получение данных из стандартного ввода, как потока байтов. После создания объекта вызов cin.tie возвращается &cout .
Например, .
В этом примере задает бит сбоя в потоке, cin когда он встречает нечисловые символы. Программа очищает бит сбоя и удаляет недопустимый символ из потока, чтобы продолжить.
Указывает глобальный поток clog .
Возвращаемое значение
Комментарии
Этот объект управляет вставкой с буферизацей в стандартный вывод ошибок в виде байтового потока.
Например, .
См. cerr с примером использования clog .
Указывает глобальный поток cout .
Возвращаемое значение
Комментарии
Этот объект управляет вставкой в стандартный вывод в виде байтового потока.
Например, .
См. cerr с примером использования cout .
wcerr
Указывает глобальный поток wcerr .
Возвращаемое значение
Комментарии
Этот объект управляет вставкой без буферизации в стандартный вывод ошибок в виде двухбайтового потока. После создания объекта выражение wcerr.flags & unitbuf ненулевое. Дополнительные сведения см. здесь: wcerr.flags и unitbuf .
Например, .
См. cerr с примером использования wcerr .
Указывает глобальный поток wcin .
Возвращаемое значение
Комментарии
Этот объект управляет извлечением из стандартного ввода в виде двухбайтового потока. После создания объекта вызов wcin.tie возвращается &wcout .
Например, .
См. cerr с примером использования wcin .
wclog
Указывает глобальный поток wclog .
Возвращаемое значение
Комментарии
Этот объект управляет вставкой с буферизацей в стандартный вывод ошибок в виде двухбайтового потока.
Например, .
См. cerr с примером использования wclog .
wcout
Указывает глобальный поток wcout .
Возвращаемое значение
Комментарии
Этот объект управляет вставкой в стандартный вывод в качестве широкого потока.
Например, .
См. cerr с примером использования wcout .
Экземпляры CString в операторе wcout необходимо привести к const wchar_t* , как показано в следующем примере.
Declares objects that control reading from and writing to the standard streams. This include is often the only header you need to do input and output from a C++ program.
Syntax
Remarks
The objects fall into two groups:
cin , cout , cerr , and clog are byte oriented, doing conventional byte-at-a-time transfers.
wcin , wcout , wcerr , and wclog are wide oriented, translating to and from the wide characters that the program manipulates internally.
Once you do certain operations on a stream, such as the standard input, you can't do operations of a different orientation on the same stream. Therefore, a program can't operate interchangeably on both cin and wcin , for example.
All the objects declared in this header share a peculiar property — you can assume they're constructed before any static objects you define, in a translation unit that includes . Equally, you can assume that these objects aren't destroyed before the destructors for any such static objects you define. (The output streams are, however, flushed during program termination.) Therefore, you can safely read from or write to the standard streams before program startup and after program termination.
This guarantee isn't universal, however. A static constructor may call a function in another translation unit. The called function can't assume that the objects declared in this header have been constructed, given the uncertain order in which translation units participate in static construction. To use these objects in such a context, you must first construct an object of class ios_base::Init .
Global Stream Objects
Name | Description |
---|---|
cerr | Specifies the cerr global stream. |
cin | Specifies the cin global stream. |
clog | Specifies the clog global stream. |
cout | Specifies the cout global stream. |
wcerr | Specifies the wcerr global stream. |
wcin | Specifies the wcin global stream. |
wclog | Specifies the wclog global stream. |
wcout | Specifies the wcout global stream. |
The object cerr controls output to a stream buffer associated with the object stderr , declared in .
Return Value
Remarks
The object controls unbuffered insertions to the standard error output as a byte stream. Once the object is constructed, the expression cerr.flags & unitbuf is nonzero, and cerr.tie() == &cout . For more details, see cerr.flags and unitbuf .
Example
Specifies the cin global stream.
Return Value
Remarks
The object controls extractions from the standard input as a byte stream. Once the object is constructed, the call cin.tie returns &cout .
Example
In this example, cin sets the fail bit on the stream when it comes across non-numeric characters. The program clears the fail bit and strips the invalid character from the stream to continue.
Specifies the clog global stream.
Return Value
Remarks
The object controls buffered insertions to the standard error output as a byte stream.
Example
See cerr for an example of using clog .
Specifies the cout global stream.
Return Value
Remarks
The object controls insertions to the standard output as a byte stream.
Example
See cerr for an example of using cout .
wcerr
Specifies the wcerr global stream.
Return Value
Remarks
The object controls unbuffered insertions to the standard error output as a wide stream. Once the object is constructed, the expression wcerr.flags & unitbuf is nonzero. For more details, see wcerr.flags and unitbuf .
Example
See cerr for an example of using wcerr .
Specifies the wcin global stream.
Return Value
Remarks
The object controls extractions from the standard input as a wide stream. Once the object is constructed, the call wcin.tie returns &wcout .
Example
See cerr for an example of using wcin .
wclog
Specifies the wclog global stream.
Return Value
Remarks
The object controls buffered insertions to the standard error output as a wide stream.
Example
See cerr for an example of using wclog .
wcout
Specifies the wcout global stream.
Return Value
Remarks
The object controls insertions to the standard output as a wide stream.
Example
See cerr for an example of using wcout .
CString instances in a wcout statement must be cast to const wchar_t* , as shown in the following example.
Declares objects that control reading from and writing to the standard streams. This include is often the only header you need to do input and output from a C++ program.
Syntax
Remarks
The objects fall into two groups:
cin , cout , cerr , and clog are byte oriented, doing conventional byte-at-a-time transfers.
wcin , wcout , wcerr , and wclog are wide oriented, translating to and from the wide characters that the program manipulates internally.
Once you do certain operations on a stream, such as the standard input, you can't do operations of a different orientation on the same stream. Therefore, a program can't operate interchangeably on both cin and wcin , for example.
All the objects declared in this header share a peculiar property — you can assume they're constructed before any static objects you define, in a translation unit that includes . Equally, you can assume that these objects aren't destroyed before the destructors for any such static objects you define. (The output streams are, however, flushed during program termination.) Therefore, you can safely read from or write to the standard streams before program startup and after program termination.
This guarantee isn't universal, however. A static constructor may call a function in another translation unit. The called function can't assume that the objects declared in this header have been constructed, given the uncertain order in which translation units participate in static construction. To use these objects in such a context, you must first construct an object of class ios_base::Init .
Global Stream Objects
Name | Description |
---|---|
cerr | Specifies the cerr global stream. |
cin | Specifies the cin global stream. |
clog | Specifies the clog global stream. |
cout | Specifies the cout global stream. |
wcerr | Specifies the wcerr global stream. |
wcin | Specifies the wcin global stream. |
wclog | Specifies the wclog global stream. |
wcout | Specifies the wcout global stream. |
The object cerr controls output to a stream buffer associated with the object stderr , declared in .
Return Value
Remarks
The object controls unbuffered insertions to the standard error output as a byte stream. Once the object is constructed, the expression cerr.flags & unitbuf is nonzero, and cerr.tie() == &cout . For more details, see cerr.flags and unitbuf .
Example
Specifies the cin global stream.
Return Value
Remarks
The object controls extractions from the standard input as a byte stream. Once the object is constructed, the call cin.tie returns &cout .
Example
In this example, cin sets the fail bit on the stream when it comes across non-numeric characters. The program clears the fail bit and strips the invalid character from the stream to continue.
Specifies the clog global stream.
Return Value
Remarks
The object controls buffered insertions to the standard error output as a byte stream.
Example
See cerr for an example of using clog .
Specifies the cout global stream.
Return Value
Remarks
The object controls insertions to the standard output as a byte stream.
Example
See cerr for an example of using cout .
wcerr
Specifies the wcerr global stream.
Return Value
Remarks
The object controls unbuffered insertions to the standard error output as a wide stream. Once the object is constructed, the expression wcerr.flags & unitbuf is nonzero. For more details, see wcerr.flags and unitbuf .
Example
See cerr for an example of using wcerr .
Specifies the wcin global stream.
Return Value
Remarks
The object controls extractions from the standard input as a wide stream. Once the object is constructed, the call wcin.tie returns &wcout .
Example
See cerr for an example of using wcin .
wclog
Specifies the wclog global stream.
Return Value
Remarks
The object controls buffered insertions to the standard error output as a wide stream.
Example
See cerr for an example of using wclog .
wcout
Specifies the wcout global stream.
Return Value
Remarks
The object controls insertions to the standard output as a wide stream.
Example
See cerr for an example of using wcout .
CString instances in a wcout statement must be cast to const wchar_t* , as shown in the following example.
Для создания программы на C++ нам нужны, как минимум, две вещи: текстовый редактор для набора кода и компилятор для превращения этого кода в приложение. При этом для компиляции необходимо запускать консоль или терминал. Однако есть и более удобный способ - использование различных сред разработки или IDE. Они, как правило, содержит встроенный текстовый редактор, компилятор и позволяют скомпилировать и запустить программу по одному клику мыши, а также имеют еще множество разных вспомогательных возможностей.
После загрузки и запуска установщика Visual Studio в нем необходимо отметить пункт "Разработка классических приложений на C++":
Выбрав все необходимые пункты, нажмем ОК для запуска установки. После установки Visual Studio создадим первый проект. Для этого перейдем в меню File (Файл) -> New (Создать) -> Project. (Проект) , и нам откроется окно создания нового проекта. В нем перейдем в левой части окна к языку С++ и выберем его подсекцию General :
В центральной части окна в качестве типа проекта выберем Empty Project , а внизу окна в поле для имени проекта дадим проекту имя HelloApp и нажмем на ОК для создания проекта.
После этого Visual Studio создаст пустой проект. Добавим в него текстовый файл для набора исходного кода. Для этого в окне Solution Explorer (Обозреватель решений) нажмем правой кнопкой мыши на узел Source Files и в контекстом меню выберем Add -> New Item. :
Затем нам откроется окно для добавления нового элемента:
Здесь нам надо выбрать пункт C++ File(.cpp) , а внизу окна укажем для файла имя Hello.cpp . Как правило, исходные файлы на C++ имеют расширение .сpp .
После добавления файла изменим опции проекта. Для этого перейдем к пункту меню Project -> Properties :
И в открывшемся окне свойств проекта в левой части перейдем к секции Linker ->System и далее для поля SubSystem установим значение Console(/SUBSYSTEM:CONSOLE) , выбрав нужный элемент в списке:
Тем самым мы указываем, что мы хотим создать консольное приложение. После установки этого значения нажмем на кнопку "Применить", чтобы новые настройки конфигурации вступили в силу.
После добавления файла проект будет иметь следующую структуру:
Вкратце пробежимся по этой структуре. Окно Solution Explorer содержит в решение. В данном случае оно называется HelloApp. Решение может содержать несколько проектов. По умолчанию у нас один проект, который имеет то же имя - HelloApp. В проекте есть ряд узлов:
External Dependencies : отображает файлы, которые используются в файлах исходного кода, но не являются частью проекта
Header Files : предназначена для хранения заголовочных файлов с расширением .h
Resource Files : предназначена для хранения файлов ресурсов, например, изображений
Source Files : хранит файлы с исходным кодом
Теперь собственно создадим первую программу и определим в файле Hello.cpp простейший код, который будет выводить строку на консоль:
Здесь использован весь тот код, который был рассмотрен в предыдущих темах про компиляцию с помощью g++.
Теперь запустим программу. Для этого в Visual Studio нажмем на сочетание клавиш Ctrl+F5 или выберем пункт меню Debug -> Start Without Debugging :
После этого на жестком диске в проекте в папке Debug можно увидеть скомпилированный файл exe, который мы можем запускать независимо от Visual Studio:
В данном случае файл HelloApp.exe как раз и представляет скомпилированный исполняемый файл. И, кроме того, в той же папке автоматически генерируются два вспомогательных файла:
HelloApp.ilk : файл "incremental linker", который используется компоновщиком для ускорения компоновки
Читайте также: