рефераты конспекты курсовые дипломные лекции шпоры

Реферат Курсовая Конспект

Streams

Streams - раздел Философия, Data Structures and Algorithms in C++ Input And Output In C++ Is Based On The Concept Of A Stream. A Stream Is A Se...

Input and output in C++ is based on the concept of a stream. A stream is a sequence of bytes that flow from something to something else. The process of output involves moving bytes, one at a time, from a program to a device. This device could be a monitor, a printer, or even a file on a hard drive. Input is the opposite. Input involves the flow bytes from a device (a keyboard, a file, a network connection) into the program.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: #include <string>#include <cstdlib>#include <iostream> using namespace std; int main(int argc, char* argv[]) { cout << "Enter your name: "; string name; cin >> name; cout << "Hello " << name; return EXIT_SUCCESS;}
Listing 1 Stream based output

Listing 1 is a simple example of stream based input and output. The above code first streams data (the characters in the text string "Enter your name: ") from the program to a device (the console) in line 9. Stream based output operations use the << operator to indicate the data to write to the stream. The stream used in this line is the output stream referenced by object cout. This object is of type ostream, which is short for "output stream."

The program in Listing 1 then streams data from the keyboard into the program, storing the user entered text in the variable name. Stream input operations use the >> operator to specify the variable where the program should place the data it reads from the stream. The stream used in this line is the input stream referenced by object cin. The cin object is of type istream, which is short for "input stream." The listing then again streams output to the console. In line 14, we see that we can place more than one piece of data into the stream in one statement.

We can open and use streams to read and write data to and from many devices besides the console. For example, a program can use a file output stream to write data to the file system. Network communication through sockets is also stream based.

– Конец работы –

Эта тема принадлежит разделу:

Data Structures and Algorithms in C++

Compiling and Running a C Program C Background History C is a modern object oriented programming language that supports... Table Different problems with similar solutions Each of the problems... Vectors...

Если Вам нужно дополнительный материал на эту тему, или Вы не нашли то, что искали, рекомендуем воспользоваться поиском по нашей базе работ: Streams

Что будем делать с полученным материалом:

Если этот материал оказался полезным ля Вас, Вы можете сохранить его на свою страничку в социальных сетях:

Все темы данного раздела:

Assessments
· Multiple-Choice Quiz 1 Recommended Exercise 1 1.3.1 Data Types Fundamental Data Types As in most other programming languages including Java, C+

Strings
In C++, the string data type provides the necessary abstraction to allow C++ programmers to work with character strings. The Java counterpart is actually two separate classes. Unlike its J

Strings
В C ++, тип данных string обеспечивает необходимую абстракцию, чтобы позволить программистам работать со строками символов. В Java фактически образуют два отдельных класса. В отличие от Ja

Creating New Data Type Names
It is possible in C++ for a programmer to create additional names for existing data types. Creating another name uses the keyword typedef. The syntax to create a new name is as follows. typed

Создание новых имен типов данных.
В C++ есть возможность создать дополнительно к существующим собственные типы данных с новым именем. Для этого необходимо использовать ключевое слово typedef. Синтаксис, чтобы создать новое имя след

Constructors
Constructors are the methods of a class that define what actions to take when creating an object. A C++ class can have multiple constructors. This allows variation in object instantiation since dif

The Destructor
A destructor is a special member function of a C++ class called when an object's lifetime ends. Like a copy constructor, only one destructor can exist for a class. Since they execute when an object

Declaration vs. Definition
In this discussion on the specification of classes in C++, the term "definition" has been used regarding functions. When we "define" a function, we dictate the function's behavi

Basic Syntax
Класс - основная единица абстракции в C++. Давайте сначала рассмотрим простой класс, определенный в Java, и затем соответствующую версию в C++. ………………………………………………………………………………… Сле

Constructors
Конструктор создает и инициализирует новый экземпляр класса. В C++ класс может иметь несколько конструкторов. Это позволяет вносить изменение в экземпляры класса включая типы параметров и значения,

Declaration vs. Definition
В обсуждении о спецификации классов, термин "definition" ("определение") был использован относительно функции. Когда мы "definition" функцию, мы определяем поведение ф

Using the Standard Streams
Three specific streams are always available throughout the lifetime of every C++ program. These are the standard input, standard output, and standard error streams. Each of these standard streams h

File Input and Output
File based input and output is similar to the mechanisms for keyboard and screen I/O. The main difference is that programmers must explicitly open and close files. In pseudocode, a generic program

Some Common Pitfalls
  A common mistake for many new C++ programmers is to reverse the << and >> operators. A good way to remember which operator to use is to think of them as arrows. You alwa

Streams
Ввод и вывод в C ++ основан на понятии потока. Поток - последовательность байтов, которые вытекают из одного в другое. Процесс продукции вовлекает байты, по одному, с программы на устройство. Это у

Using the Standard Streams
Три определенных потока всегда доступны всюду в C ++ программах. Это standard input, standard output, and standard error потоки. У каждого из этих стандартных потоков есть определенное использовани

File Input and Output
Файл вход и выход подобен механизмам для ввода / вывода экрана и клавиатуры. Главное различие - то, что программисты должны явно открыть и закрыть файлы. В псевдокоде главная программа, которая чит

Some Common Pitfalls
Частая ошибка для многих новых C ++ программисты состоит в том, чтобы полностью изменить << и >> операторы. Хороший способ помнить, какой оператор использовать должен думать о них как о

Text Substitution
The preprocessor is a tool that C++ programmers use to manipulate the contents of source code files prior to compilation. In the most general sense, the preprocessor performs text substitution and

File Inclusion
File inclusion is a feature of the C++ preprocessor that allows a source code file to use shared code. We consider shared code to be classes or functions declared in other files. In C++, we can onl

Macro Substitution
The C++ preprocessor can perform a programmer defined text substitution throughout an entire source code file. This is known as macro substitution. Programmers define a macro using the #define prep

Conditional Compilation
Beyond macro substitution, a more important reason to use #define is to support conditional compilation. Using #define, and some other preprocessor directives, we can instruct the compiler to compi

An Example: Assumption Verification
Verifying assumptions using assertions is an example of a common use of the preprocessor and its features. An assertion is a statement placed in source code to verify an assumption. Usually, progra

Text Substitution
Препроцессор это инструмент, чтобы управлять содержанием файлов исходного текста до компиляции. В самом общем смысле препроцессор выполняет текстовую замену и текстовую модификацию. Высокоуровневые

File Inclusion
Включение файла - особенность C++ препроцессор, который позволяет файлу исходного текста использовать разделенные коды. Мы полагаем, что разделенный код это классы или функции, объявленные в других

Macro Substitution
C++ препроцессор может определить текстовую замену всюду по всему файлу исходного текста. Это известно как макро-замена. Программисты реализуют макро-замену директивой #define препроцессора, котора

Conditional Compilation
Вне макро-замены важная причина использовать #define состоит в том, чтобы поддержать условную трансляцию. Используя #define, и некоторые другие директивы препроцессора, мы можем проинструктировать

An Example: Assumption Verification
Подтверждение предположений, используя утверждения является примером обычного использования препроцессора и его особенностей. assertion - утверждение, помещенное в исходный текст, чтобы проверить п

Хотите получать на электронную почту самые свежие новости?
Education Insider Sample
Подпишитесь на Нашу рассылку
Наша политика приватности обеспечивает 100% безопасность и анонимность Ваших E-Mail
Реклама
Соответствующий теме материал
  • Похожее
  • Популярное
  • Облако тегов
  • Здесь
  • Временно
  • Пусто
Теги