0

In the following code,i have restricted that number of characters to be written on the file must be LESS than 15,& the characters written are exactly 15(as desired),when i read back the file.But the first WHILE loop is not working as desired,it should have to be skipped & STOP receving input from the user,when the counter variable have a value 15, but it is yet receiving input from user,till he/she not presses enter

#include<iostream>
#include<conio.h>
#include<string.h>
#include<fstream>

using namespace std;

int main()
{
   int i=0;
   ofstream out("my_file",ios::out|ios::binary); //'out' ofstream object
   char ch1;

 while(i<15)                       //receiving input even when i>15,till 'enter' IS pressed
 {
     cin>>ch1;      
     out.put(ch1);
     i++;

 }

 out.close();

 char ch;
ifstream in("my_file"); //'in' ifstream object

while(1)
{
    in.get(ch);
    if(in)cout<<ch;
}
in.close();
_getch();
return 0;
    }

2 Answers 2

1

Standard I/O functions work only after pressing Enter. To get desired effect, you need to use _getch, which reads every symbol immediately. Notice that _getch is not portable.

Sign up to request clarification or add additional context in comments.

1 Comment

One could always use a platform specific method. In some Windowing / GUI systems, single characters are sent via messages.
1

input is almost always line buffered, so when a program reads from the command line, it almost always blocks until there is an entire line available at the input.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.