Click to See Complete Forum and Search --> : While Loop ASCII Enter Key


pechos21
December 15th, 2004, 02:54 PM
I am writing a program that asks the user for a file name, and displays the file contents on the screen. If the contents wont fit on a single screen, the program should display 24 lines of output at a time and then pause. Each time the program pauses it should wait for the user to strike the enter key before the next 24 lines are displayed.

The following code opens a file and displays the first 24 lines of code although I cannot get the next 24 lines of code to display upon pressing the enter key. I am wondering if the problem is in the last loop What is the ASCII number for the enter key, and how do i fix the loop
Thanks pechos

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
fstream nameFile;
char input[81], fileName[81];

cout<< "Enter a file name: ";
cin >> fileName;

nameFile.open(fileName, ios::in);
if (!nameFile)
{
cout << fileName << " could not be opened.\n";

return 0;

}

int counter =0;
nameFile.getline(input,81);
char c =' ';
while (!nameFile.eof())
{
cout << input << endl;
nameFile.getline(input, 81);
counter++;
if (counter == 24)
{

cin.get >> c;
while(c != '13')
cin.get >> c;
counter = 0;

}
}
nameFile.close();

return 0;
}

kakalake
December 15th, 2004, 04:53 PM
I changed the code so it should do what you want....


#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>

using namespace std;

int main()
{
string input, fileName;

cout << "Enter a file name: ";
getline( cin, fileName );

ifstream nameFile( fileName.c_str() );
if (!nameFile )
{
cerr << fileName << " could not be opened.\n";
return 0;
}

int count = 0;
while( nameFile )
{
getline(nameFile, input);
cout << input << endl;
++count;

if( count==24 )
{
_getch();
count=0;
}
}
nameFile.close();
return 0;
}


hope i could help you

Bni
December 15th, 2004, 05:26 PM
My first suggestion is for usage of indentation.
Your code will be much more attractive to read.

My second is for developing self-confidence.
Make abundant use of instructions like
cout >> "I am here" >> endl;
to find out where your code may go wrong.
After a while you'll be glad and proud of your results.

You will find that answers like these are easy.

A return key is \n.

cin >> c OK!
c = cin.get() Ok!
cin.get >> c No!


JF Jolin