2011-08-30 147 views
0

在下面的代码中,我限制写入文件的字符数必须小于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; 
    } 

回答

1

标准I/O功能只有在按下Enter后才起作用。为了获得理想的效果,您需要使用_getch,它立即读取每个符号。注意_getch不可移植。

+0

人们总是可以使用平台特定的方法。在某些Windowing/GUI系统中,单个字符通过消息发送。 –

1

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