C++ 文件输入输出
在下面的代码中,我限制了当我读回文件时,写入文件的字符数必须少于15,并且写入的字符数正好是15(根据需要)。但是第一个WHILE循环没有按要求工作,应该跳过它并停止接收用户的输入,当计数器变量的值为15时, 但它仍在接收用户的输入,直到 他/她没有按回车键C++ 文件输入输出,c++,file,io,C++,File,Io,在下面的代码中,我限制了当我读回文件时,写入文件的字符数必须少于15,并且写入的字符数正好是15(根据需要)。但是第一个WHILE循环没有按要求工作,应该跳过它并停止接收用户的输入,当计数器变量的值为15时, 但它仍在接收用户的输入,直到 他/她没有按回车键 #include<iostream> #include<conio.h> #include<string.h> #include<fstream> using namespace std;
#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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
int i=0;
ofstream out(“我的文件”,ios::out | ios::binary);/“out”of stream对象
char ch1;
而(i15,直到按下“回车”键
{
cin>>ch1;
输出(ch1);
i++;
}
out.close();
char ch;
ifstream in(“我的文件”);/“在”ifstream对象中
而(1)
{
in.get(ch);
如果(在)cout标准I/O函数只有在按Enter键后才能工作。为了获得想要的效果,您需要使用_getch,它可以立即读取每个符号。请注意_getch是不可移植的。输入几乎总是行缓冲的,因此当程序从命令行读取时,它几乎总是阻塞,直到在inpu上有一整行可用t、 可以始终使用特定于平台的方法。在某些窗口/GUI系统中,单个字符通过消息发送。