text: Input and output functionality is not defined as part of the core C++ language, but rather is provided through the C++ standard library (and thus resides in the std namespace). In previous lessons, you included the iostream library header and made use of the cin and cout objects to do simple I/O. In this lesson, we’ll take a look at the iostream library in more detail.
  The iostream library
  When you include the iostream header, you gain access to a whole hierarchy of classes responsible for providing I/O functionality (including one class that is actually named iostream). The class hierarchy for the non-file-I/O classes looks like this:
  The first thing you may notice about this hierarchy is that it uses multiple inheritance (that thing we told you to avoid if at all possible). However, the iostream library has been designed and extensively tested in order to avoid any of the typical multiple inheritance problems, so you can use it freely without worrying.
  Streams
  The second thing you may notice is that the word “stream” is used an awful lot. At its most basic, I/O in C++ is implemented with streams. Abstractly, a stream is just a sequence of characters that can be accessed sequentially. Over time, a stream may produce or consume potentially unlimited amounts of data.
  Typically we deal with two different types of streams. Input streams are used to hold input from a data producer, such as a keyboard, a file, or a network. For example, the user may press a key on the keyboard while the program is currently not expecting any input. Rather than ignore the users keypress, the data is put into an input stream, where it will wait until the program is ready for it.
  Conversely, output streams are used to hold output for a particular data consumer, such as a monitor, a file, or a printer. When writing data to an output device, the device may not be ready to accept that data yet -- for example, the printer may still be warming up when the program writes data to its output stream. The data will sit in the output stream until the printer begins consuming it.
  Some devices, such as files and networks, are capable of being both input and output sources.
  The nice thing about streams is the programmer only has to learn how to interact with the streams in order to read and write data to many different kinds of devices. The details about how the stream interfaces with the actual devices they are hooked up to is left up to the environment or operating system.
  Input/output in C++
  Although the ios class is generally derived from ios_base, ios is typically the most base class you will be working directly with. The ios class defines a bunch of stuff that is common to both input and output streams. We’ll deal with this stuff in a future lesson.
  The istream class is the primary class used when dealing with input streams. With input streams, the extraction operator (>>) is used to remove values from the stream. This makes sense: when the user presses a key on the keyboard, the key code is placed in an input stream. Your program then extracts the value from the stream so it can be used.
  The ostream class is the primary class used when dealing with output streams. With output streams, the insertion operator (<<) is used to put values in the stream. This also makes sense: you insert your values into the stream, and the data consumer (eg. monitor) uses them.
  The iostream class can handle both input and output, allowing bidirectional I/O.
  Finally, there are a bunch of classes that end in “_withassign”. These stream classes are derived from istream, ostream, and iostream (respectively) with an assignment operator defined, allowing you to assign one stream to another. In most cases, you won’t be dealing with these classes directly.
  Standard streams in C++
  A standard stream is a pre-connected stream provided to a computer program by its environment. C++ comes with four predefined standard stream objects that have already been set up for your use. The first three, you have seen before:
  Unbuffered output is typically handled immediately, whereas buffered output is typically stored and written out as a block. Because clog isn’t used very often, it is often omitted from the list of standard streams.
  A basic example
  Here’s an example of input and output using the standard streams:
  In the next lesson, we’ll take a look at some more I/O related functionality in more detail.
  Explain input and output library header file in C++.
  sir where can i find a tutoriol on stacks,queues and linked list on the site learncpp.com
  I haven’t written them yet. They’re still on my to-do list. I plan to tackle those after I finish rewriting the lessons on inheritance (and maybe template classes).
  If cin, cout are predefined objects of istream_withassign and ostream_withassign, then how does including iostream into the program works?
  #including iostream copies in the class definitions for all of those classes, so the compiler knows what they are.
  “When you include the iostream header, you gain access to a whole heirarchy of classes responsible for providing I/O functionality (including one class that is actually named iostream). The class heirarchy for the non-file-I/O classes looks like this.”
  "heirarchy" should be replaced with "hierarchy" in this paragraph (twice).
  Also in "At it’s most basic" (right at the beginning of the "Streams" section), "it’s" should be replaced with "its".
  Fixed, thanks
  I cannot compile the example code with the exit(1); line in the if statement: "error: ‘exit’ was not declared in this scope". Why?
  I work with Code::Blocks 16.01 on W7 with GNU C++. Many thanks for your advice.
  The code didn’t include cstdlib. I’ve updated the example, and it should compile now.
  Many thanks. Your tutorial is excellent. I learned in a short time much more than from any other textbook or in-class course.
  A standard stream is a pre-connected stream provided to a computer program by its environment. C++ comes with four predefined standard stream objects that have already been set up for your use.
  The first two, you have seen before
  actually, we’ve seen cerr aswell
  Can you help me with this?
  Which one is more powerful between curses and conio??
  Conio is Windows-specific, non-standard, AND deprecated. Don’t use it.
  Hey Alex,
  You said conio is windows specific and its deprecated, so its use must be stopped. That must be the reason why Microsoft stopped shipping it with its MSVC package in visual studio. But yesterday, I tried on VS 2017 and it worked with conio.h. But I remember earlier it didn’t work that way so why is that working now? Could it be that they came up with some safer version of it?
  It’s probably provided for backwards compatibility reasons. But I can’t speak to Microsoft’s motives here.
  Whats difference between pdcurses, ncurses and curses?
  And how to work with them I have seen some tutorials on net but they all have rather confused me about the process?
  The wikipedia article on ncurses has a good history of curses. Looks like ncurses might be the only one still updated today.
  As for how to work with them, I’m afraid I can’t help you there. You’ll have to find other online resources. 🙁
  My requirement is that, I want to create a login system which would accept password and it will be shown in "******" while entering it. So I require a non-echoing and unbuffered input. This facility was available in conio.h, earlier I used getch() for such purpose in gcc compiler. But then I got advice form my teachers that I should use visual studio that perfectly follows all the standards of c++ and is a must use IDE for every programmer. But in visual studio conio.h is not available 🙁
  And ncurses is also for linux (I have read on internet that it is not available for windows)?
  According to you, Should I shift from standard c++ to such non-standard c++ for I/O functionality?
  ncurses is available for windows… Checkout PDCurses. I’ve used it on a personal project I was working on, and it works great for doing unbuffered non-echoing I/O.
  That way you’ll be able to stick with standard C++, just with a dependency on a well-regarded cross-platform library.
  So is there any way in standard c++ to get input without hitting enter??
  No, standard C++ does not include any functionality to do this.
  If you want to do something like this, I recommend checking out the ncurses library. It has the ability to do this, and more!
  Hey, I have figured out one solution can we say it in this way that ">>" is the standard stream extraction operator which works on white spaces (it needs a white space until which it would read the text) so we need to hit an enter (white space) to receive data through cin.
  So can we use getline() or get() to get text immediately (before user presses enter key) ??
  No, std::cin will stop extracting a string as soon as it hits the first space (whitespace), but it won’t process your input until you hit enter. Similarly, getline() will wait for you to hit enter before processing.
  So after pressing enter my text finally goes into the buffer for further extraction..Thanks a lot!!!
  Another thing, I have got to know about echoing, as much as I understand whenever some text is entered it is also sent to the standard output file (monitor) but if I press backspace once,before pressing enter then one character is withdrawn from the output file also (which seems like a action response system). So there must be some backup copy being generated of the text that we entered and has been extracted for all this functionality to take place but you said "With cin, once the data is extracted, it’s gone". But the same text has to be placed in the output file before it is in the buffer so that user can see what he is typing and before pressing enter user can correct his input.
  So is this all about echoing or I am lacking somewhere??
  Good question. When you press a letter and it’s immediately reflected on the screen, that is definitely echoing. However, I don’t actually know how what you’re typing (before you hit enter) is stored while you’re still typing it. It’s unclear to me if that’s going into the cin buffer (with characters being removed when you hit backspace), or whether it’s going into an intermediary buffer. Ultimately, it doesn’t really matter, so long as the behavior is consistent.
  So what is the use of ‘\r’ here? What function does it performs here? And what does carriage return means?
  Can it be said that ‘\r’ is like the send button where user enter some text and is free to edit it but after pressing send button (‘\r’) the text entered by user goes into the buffer?
  Another thing in your example after extraction of 4, ‘a’ remains in the buffer so just like file handling, can we re-read a previously read data by shifting file pointer backwards. Can we do the same with cin or the data once extracted gets lost forever??
  “Carriage return” is a historical term for ‘\r’, which moved the “carriage” (the printer head) back to the beginning of the line it was printing on. In modern operating systems, printing a ‘\r’ character to the screen tells the console to go back to the beginning of the current line. However, not all consoles will respect this.
  Modern C++ uses ‘\n’ as a carriage return + new line character. When you press enter, a ‘\n’ character is placed into the input stream. You generally can not edit text once it’s in the buffer -- you can only extract it or clear it.
  With cin, once the data is extracted, it’s gone.
  So here ‘\r’ is the input extraction command??
  But why is a command required to extract input, code can simply take input as when a key is pressed by the user??
  I am not able to understand the whole process, user presses enter to send his input to the code. But then from user’s point of view it is similar to flushing because it is his decision whether to let code extract the data or not, by pressing enter he allows code to extract the data (which equivalent to the process of flushing, changes made on data are overwritten on the file i.e. changes made are reflected to the other end). Code is dependent on user to extract the data. The extraction of data is for the code(it is code’s part) which means code should to it on it’s own but code is not able to take data until and unless user presses enter.
  In a nutshell user controls the extraction of data??
  > So here ‘\r’ is the input extraction command??
  No, operator>> is the input extraction operator. ‘\r’ is an output character to deal with carriage returns, it doesn’t have much to do with input.
  Flushing is the process of pushing all buffered output to the destination (e.g. a file or database), which clears the buffer. Consider the following:
  If the user types “4a”, the 4 will be extracted to variable x, but character ‘a’ will not be. That ‘a’ will be stuck in the buffer, waiting a future extraction. There’s no flushing going on here, and nothing similar to flushing. Just extraction.
  The user inputs the data, the code controls the extraction.
  ->Hey Alex, Is cin a buffered stream?? I am asking this because each time to submit some input I need to press enter into the console window, So does it mean that enter acts as a flushing command like endl?
  ->Recently I got to know that enter key is ‘r’ but while reading through cin it becomes ‘r”n’ because of standard text file reading conversions so is ‘r’ a flushing request for cin?
  ->What does flushing mean while reading a file, if I will flush a file while reading it? Where will the changes be reflected back? To the file?? But here the file is keyboard (standard input device) which does not keeps any record of what was pressed by the user.
  Yes, cin is buffered, and will store input that hasn’t been extracted yet. Flushing doesn’t have any meaning in the context of input (where would you flush the input to?). Input can only be extracted or cleared.
  I found a couple places where "it’s" should be "its":
  * "…for example, the printer may still be warming up when the program writes data to it’s output stream."
  * "A standard stream is a pre-connected stream provided to a computer program by it’s environment."
  Fixed. Thanks!
  One more thing if i add ios::ate at the place of out the code totally stops working. Plz help me through this I need to create a project for this year and it must include filehandling.
  Hey Alex,
  How are you man i’m again back with some more problems related to file handling.
  ->First thing could you please clear me with the difference between different modes of opening a file(ios::out,ios::in,ios::ate,ios::app)
  ->Secondly I have a problem while working with files practically see this program of mine…..
  CODE:
  int main ()
  {
  char p[80];
  fstream file("text1.txt",ios::out|ios::in);
  cout<<"Starting position of the file is "<<file.tellg()<<endl;
  getch();
  if(file.is_open())
  cout<<"file is openn";
  else
  cout<<"file is not openn";
  getch();
  file<<"Hello man how are you";
  file.seekp(0);
  while(!file.eof())
  {
  file>>p;
  cout<<p<<endl;
  }
  cout<<"nThe current position of the file pointer is "<<file.tellg();
  file.seekp(0);
  if(file.eof())
  cout<<"nAt the eof";
  while(!file.eof())
  {
  file>>p;
  cout<<p<<endl;
  }
  file.close();
  return 0;
  }
  Output:
  Starting position of the file is 0
  file is open
  Hello
  man
  how
  are
  you
  ->Third thing is that i’m not able to work properly with files as my codes suddenly crash with a lots of errors sometimes they work properly and when compiled again end up with errors.I am not able to understand what and how the data is being transferred could please show me some codes illustrating how to do that.
  Thanks a lot man you really helped me with the file handling.Your explanations were the best that i could find.Although i still have some doubts in file handling but they are associated with coding not with working of buffer and streams.I may clear them later i should not bother you a lot.Again thanks!!! 🙂
  So what is the difference between ‘\n’ and endl??
  I have read a lot on the internet and only got the difference related to flushing.
  ‘\n’ is just a newline. std::endl is both a newline and a flush request (which will be ignored if the stream isn’t buffered).
  Ok one more thing we know that std::cout is a unbuffered stream but endl keyword ends the line and also flushes the contents into the file(monitor) how is it possible(as std::cout does not have a buffer)??
  Another thing is that what is "curses" in your last comment??
  There’s no requirement that std::cout be unbuffered. If the stream is unbuffered, then endl will add a newline but not flush anything (because there’s nothing to flush with an unbuffered stream).
  Curses is an I/O library. There have been various forks of it, such as ncurses and PDcurses. If you need more control over I/O functionality (such as if writing an ascii-based roguelike game), these would be useful.
  Hey since std::cout is buffered:
  Which means that one must flush the stream so as to get test on the file (i.e. output screen). But in practice we don’t perform something like this and still the text gets reflected to the output screen.
  No. With unbuffered output, anything sent for output must be output immediately. With buffered output, the stream can aggregate requests for performance reasons if it wants to. It may decide not to if that’s not necessary (for example, when writing to a console, there’s little reason to buffer the output).
  Flushing buffered output simply tells the stream to output everything that’s been buffered but not output yet. It guarantees that all output has actually been output. But that may have already happened anyway without an explicit flush request.
  Another theory which I got to know was we don’t face such problems because after using std::cout we often use some input stream or some other input functionality which makes the use of stdin. And in it’s implementation the first task is to flush the output buffer and then get the data from the stdin. This all happens in a flash and as a result this sort of buffering is not observed.
  Is it true?
  I’m not aware of any cases in which using std::cin flushes std::cout. I don’t know why they’d have any direct interaction -- the input buffer and output buffer are distinct.
  Yes, they are tied to each other through std::ios::tie() which is used to tie one stream to other thereby linking their functionality more details can be found at:-
  I wasn’t aware of that! But I guess it does make sense, otherwise the output line telling the user what to input may not show up before the input line executes, leaving the user with no indication of what to input.
  how can i do that all without streams could you please guide me in that???
  For files, you can use the C functions fopen(), fseek(), fread(), fwrite(), to do direct file access. You can look up how to use these on C reference sites.
  For the console, I’m not sure it’s possible to avoid streams without installing a console-I/O library like curses.
  Just a short question, when I am typing this comment, all the characters from “Just” to the end of this comment sit in stream. When I am done and hit the Post Comment button below, the data is extracted from stream to the output device. Am I right (That might be the most stupid question you ever have faced, but that is because I am not getting what stream is, what it holds, when it works, how stream is different than buffer etc.)
  It appears this article is in need of a rewrite. 🙂
  When you’re typing characters into an edit box, you’re really entering them into a buffer that has been set aside for user input. When you hit post comment, that buffer is sent to the server, which stores the data in the database. I don’t know whether streams are used for this or not.
  A buffer is simply a chunk of contiguous memory that’s used to store data. In reality, it’s probably just an array. Buffers allow read/write access to their contents.
  A stream is an abstraction that allows you to pipe data from one place to another. An example is std::cout. You send it bits of data, and it transfers that data to the console. Streams can be pointed at different kinds of input or output sources, and provide a consistent (though possibly limited) interface for accessing them. Streams normally only provide sequential access to the data (e.g. you can’t access the data out of order).
  The only place streams and buffers intersect are:
  1) A stream may make use of an internal buffer to cache data
  2) A stream may be used to read data into an external buffer
  Wait wait wait you said "buffer is external to the stream.But the stream may have its own buffer".What do you mean by this???There can be two buffers one for the file and other for the stream(Is it true?).
  ->I thought that stream was the one that had a choice either to equip a buffer for a file so that its working may smoothen up(which is also called buffered stream) or to work traditionally without a buffer(like cin and cout do).
  ->As cin,cout are unbuffered streams so they don’t store the data for the keyboard or monitor into the buffer and write data into respective files as when it is passed by the program.
  Another doubt is that consider a file working with buffer so buffer is just an linearly arrayed group of variables in some part of memory that holds the data for file and file pointer tells our position in that buffer(not in the file) with the help of tellg/tellp.So here we are accessing the data just like normal pointer by just moving its pointing location ahead or behind. so what is the use of stream here.Actually my basic doubt is associated with the mutual working of stream,buffer and the file.
  Eg.-Consider it as a buffer
  4 5 3 2 4 7 6 3 9 8 3 3 4 2 9 7 8 --->Data of 1byte each stored in the buffer
  ^ fileptr(its points the memory storing 5)
  If I start reading or writing to the file then fileptr will be just incremented and the data of upcoming bytes(containing 3 2 4 7) would be accessed. Isn’t it like the normal pointer working.So where are streams in this case??
  The stream can have its own buffer that it uses to temporarily store data it’s read or that is pending to be written. Outside of that, the program can use a buffer (or multiple buffers) to store whatever data it wants. Files don’t have their own buffers.
  Streams really just provide an abstraction to work with hardware. In the case of files, they can help manage the file pointer and file operations. You could do all of this yourself without using streams if you want. They’re just there for consistency and ease of use.
  So it all means that our stream is the in-charge. We just give our data to the stream and stream has the responsibility to store data into the buffer and extract it too whenever user flushes the file. It depends on the stream itself whether it has to store that data into a buffer temporarily or to flush it into the file immediately.Those types of streams which require most of the editing work are generally buffered.Is it right now?
  Almost!
  >.
  File I/O is a comparatively expensive operation in general, and the goal should be to minimize both the number of reads/writes and amount of data read/written. In some cases, it may make more sense to write data directly to the file (e.g. a logger appending data to the end of the file). In other cases, it might make sense to read the file into a buffer, edit the buffer, and write the buffer out.
  > Those types of streams which require most of the editing work are generally buffered.Is it right now?
  Not sure what you mean by this. Streams don’t require most of the editing work. When data is read into a buffer for purpose of editing, that buffer is external to the stream. But the stream may have its own buffer for purpose of increasing read/write performance.
  Would you please again clear those basic doubts of mine regarding opening of file,use of buffers and streams!!! I only know that when a file is opened, all the contents in that file are copied to some location in memory called as buffer and all the file reading/writing operations take place here(in buffer) as working with file consumes a lots of system resources.So as to manage this, all the editing is done into the buffer and then it is flushed.Thus all data that file was containing gets replaced with that of the buffer.If you say that stream is just a medium for the flow of data.So how does our file pointer moves in the stream while editing the data(as all the file handling operations take place in the buffer not in the file) and also then how it acts as a buffer. I am confused about the role of streams here,the storage and working of buffers and the opening and closing of file.I have also heard a buffered stream and and unbuffered stream what are they actually.Could please you help me in that too.
  First, let’s clarify some misconceptions about files. When a file is opened, the contents are _not_ automatically copied to some location in memory. Opening a file simply gives you a handle to read from or write to the file. Many programs read the contents of the file into a buffer, modify the buffer, and then overwrite the file with the contents of a buffer to update the file. This is how most text editors work. However, this is just one way to work with file data. For example, it’s not uncommon for a log tool to open a file handle, move the file pointer to the end of the file, and append data to the end of the file. In this case, data is written to the file without having to read and write the entire file (or even use a buffer at all).
  Let’s clarify some concepts:
  * A buffer is simply a chunk of memory used to hold data. A buffer is often implemented as an array of data. Modifying the data in the buffer is just making memory accesses.
  * A stream is a sequence of bytes that can continually produce or consume data.
  The main goal of streams is to abstract the user away from the details of the source that they’re reading to or writing from. Let’s say I want to write to the console (or a file, or the printer, or any other output source). If I have a stream object pointed to that source, all I need to do is put my data in the stream, and the stream figures out how to get it to the output source.
  There are two types of streams. When data is passed to an unbuffered stream, it will try and move that data to the destination immediately. For example, if I put the letters ‘a’, ‘b’, and ‘c’ in an unbuffered file output stream, it will write ‘a’, then ‘b’, then ‘c’ in sequence. With a buffered stream, the stream may opt to collect data internally (using a buffer) before writing. So if I put the letters ‘a’, ‘b’, and ‘c’ in a buffered file output stream, then it will probably write “abc” in one go. That’s more performant because there’s only one disk access instead of three, but the data may not get written immediately (so if my program crashes, the data may not have yet been written to disk).
  can u please clarify what is a handle ?
  A handle is an indirect reference to a resource (file, database, process, etc…). A handle could be implemented as a pointer, or it could be an id that references some entry in a table.
  A good analogy is your name. Your name is an example of an indirect handle to you. If I just had your name, I wouldn’t know how to find you (where would I start looking?). However, if I knew both your name and where you were located (e.g. in a particular room), then I could use your name to locate you amongst the other people.
  As you said that "Abstractly, a stream can be thought of as a sequence of bytes of infinite length that is used as a buffer to hold data that is waiting to be processed.". So what do you basically mean that stream is a buffer for our file and devices.Or it is just a medium(a flow of data) to transfer information between our program and buffer(a location in memory which stores the data that needs to be inserted into the file).These two things are really conflicting as the one told by you and the second one that other websites told?????
  I’ve updated the definition. A stream really is just a sequence of bytes that can be accessed sequentially. Over time, the stream may produce or consume potentially unlimited amounts of data.
  Abstractly, they just describe a mechanism for transfering data. Concretely, streams are often implemented using buffers or files, as data in the stream may be queued for input, output, or processing.
  Input three positive integers representing the sides of a traingle and determine whether they form a valid traingle. Hint:n a traingle the sum of any two sides must always be greater than the side.
  how i can make programme for this by c++ way???
  OK,do it like this:
  //C style without C++ class,under VC++6.0
  #include
  using namespace std;
  int main()
  {
  int a,b,c;
  do{
  printf(“a,b,c:\n”);
  scanf(“%d,%d,%d”,&a,&b,&c);
  }while(!(a+b>c && a+c>b && c+b>a));
  printf(“Correct!A valid traingle.\n”);
  return 0;
  }
  //run correctly
  #include
  using namespace std;
  int main()
  {
  int a,b,c;
  do{
  printf(“a,b,c:\n”);
  scanf(“%d,%d,%d”,&a,&b,&c);
  }while(!(a+b>c && a+c>b && c+b>a));
  printf(“Correct!A valid traingle.\n”);
  return 0;
  }
  i have qustion , any one can help me???
  In your second line in after Streams, you have “it’s”
  everyone knows possessive pronouns cannot have an apostrophe!
  Q: What is the difference between the outputs of “cout”, “cerr” & “clog” ?
  NOTE: Both of them gives exactly the same output to the screen.
  Q: Does “cerr” has any more inner workings than printing “Oops, you entered an invalid age!” to the screen?
  and
  There’s actually very little difference between them. However, it is possible to redirect one or more of the channels to file (or printer, or network, or elsewhere). That way, you can have normal output go to one place (eg. a file) and have any errors go to another place (eg. the screen).
  cout — an ostream_withassign class tied to the standard input
  should read as
  cout — an ostream_withassign object tied to the standard output
  [ You are correct. Thanks for pointing out the mistake. -Alex ]
  Abstractly, a stream can …. infinite length that “us” used as a buffer
  ===>
  Abstractly, a stream can …. infinite length that “is” used as a buffer
  [ Fixed. Thanks! -Alex]
  you got a mistake here! x is not mentioned
  #include <iostream>
  int main()
  {
  using namespace std;
  cout << "Enter your age: " << endl;
  int nAge;
  cin >> nAge;
  if (nAge <= 0)
  {
  cerr << "Oops, you entered an invalid age!" << endl;
  exit(1);
  }
  cout << "You entered " << nAge << " years old" << endl;
  return 0;
  }
  [ Fixed. -Alex ]
  simple program using stringstream
  Name (required)
  Website