一千萬個為什麽

搜索

文件輸入輸出

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
#include
#include
#include

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<

最佳答案

標準I/O功能僅在按Enter後才起作用。要獲得所需的效果,您需要使用_getch,它會立即讀取每個符號。請註意,_getch不可移植。

轉載註明原文: 文件輸入輸出