在下面的代码中,我限制了要写入文件的字符数必须小于 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 函数只有在按下 Enter 后才能工作。要获得预期的效果,您需要使用 getch,它会立即读取每个符号。请注意,getch 不可移植。
关于c++ - 文件输入输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7245201/