文件输入输出
在下面的代码中,我限制了要写入文件的字符数必须小于 15,&当我读回文件时,写入的字符正好是 15 个(根据需要)。但是第一个 WHILE 循环没有按预期工作,应该跳过它并执行它。当计数器变量的值为 15 时,停止接收用户输入, 但它尚未收到用户的输入,直到 他/她没有按 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标准 I/O 功能仅在按 Enter 后才起作用。为了获得想要的效果,您需要使用 _getch,它会立即读取每个符号。请注意,_getch 不可移植。
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.
输入几乎总是行缓冲的,因此当程序从命令行读取时,它几乎总是阻塞,直到输入处有整行可用。
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.