首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

百思不得其解

2012-02-20 
百思不得其解,请求帮助下面的一段程序功能是浏览文本文件。其中有个小小的问题。用它打开一个大于23行的文件

百思不得其解,请求帮助
下面的一段程序功能是浏览文本文件。其中有个小小的问题。用它打开一个大于23行的文件,为什么输出 "press   'enter '   key... "之前,程序就暂停等待输入?

#include <iostream.h>
#include <fstream.h>
#include <stdio.h>
#include <stdlib.h>
void   main()
{
int   r;
char   c;
fstream   file;
char   fn[15],   buf[100];
cout   < <   "Input   the   file 'name: ";
cin   > >   fn;
file.open(   fn,   ios::nocreate|ios::in   );    
//针对文件后缀为(.txt     .h     .cpp   .pas等)文件
if(   !file   )
{
cout   < <   "The   file   you   wanted   open   does   NOT   exist. ";
abort();     //#include <stdlib.h>
}
      while(   !file.eof()   )
{
r=0;
while(   !file.eof()   &&   r <23   )
{
file.getline(   buf,   100   );
cout   < <   buf   < <   endl;
r++;
}

cout   < <   "press   'enter '   key...\n ";
c   =   getchar();     //#include <stdio.h>
}
file.close();
}


[解决办法]
我运行没问题
注意buf的大小, 如果一行过长...
[解决办法]
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{
string filename;
cout < < "Input the file name: ";
cin > > filename;

ifstream ifile(filename.c_str());
if (!ifile)
{
cout < < "Couldn 't open file " < < filename < < endl;
return -1;
}

int line=1;
string buf;
while (!ifile.eof() && line <=23 )
{
getline(ifile, buf);
cout < < setfill( '0 ') < < setw(2) < < line < < ": " < < buf < < endl;
line++;
}

getchar();
cout < < "Press 'Enter ' key... " < < endl;
getchar();

ifile.close();

return 0;
}

[解决办法]
endl 与 \n 还是有差别的, endl 带有flush 。

[解决办法]
如果楼主是想控制每屏显示23行while( !file.eof() && r <23 ){file.getline( buf, 100 );
cout < < buf < < endl;r++;} 显然逻辑是错误的,改为:
while(!file.eof()){
if(r%23==0) {system( "pause ");r=1;}......} 不知楼主说的是不是这个。

热点排行