文件输入输出

file input output

本文关键字:输入输出 文件      更新时间:2023-10-16

在下面的代码中,我限制了写入文件的字符数必须小于15,&当我读回文件时,写入的字符正好是15个(如期望的那样)。但是第一个WHILE循环没有按预期工作,它应该被跳过&当计数器变量的值为15时,停止接收来自用户的输入;但它还在接收用户的输入,直到他/她没有按回车

#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;
    }

标准I/O功能需要按回车键才能工作。为了获得预期的效果,需要使用_getch,它会立即读取每个符号。注意_getch是不可移植的。

输入几乎总是行缓冲的,所以当程序从命令行读取时,它几乎总是阻塞,直到在输入处有一整行可用。