Ctrl+Z does not work when trying to exit loop

T4000 picture T4000 · Apr 15, 2012 · Viewed 7.1k times · Source

I am trying to exit a loop with Ctrl+Z, but it does not work. I have looked carefully my code, but I cannot figure out the problem. Your help will be appreciated. I am using Dev-C++. The code is just bellow:

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

using namespace std;

class student 
{
  private:
   string name;
   int age;
   double GPA;
  public:

   void read ();

};

void student::read()
{
  do
   {   //enter student data
     cout << "Name:  " ;
     cin>>name;
     cout<<"Age:  ";
     cin>>age;
     cout << "GPA:  ";
     cin>>GPA;

    cout<<"\n\n  any key to continue or Ctrl+Z to exit."<<endl<<endl;
   }
   while(getch()!=EOF);  //Ctrl+Z to exit
}


int  main()
{
  student stud;
  stud.read();
  return 0;
}

Answer

David Schwartz picture David Schwartz · Apr 15, 2012

Consoles aren't files. Consoles don't end. There is no way a console can have an end of file.

I think you've forgotten that you're using console I/O (conio.h/getch), not file I/O (stdio.h/getchar). Whatever you're thinking about EOF, it's not a console I/O thing. I can't find any documentation that suggests getch can ever return EOF, and as far as I can tell, that wouldn't make any sense.

If you want to check for a Control-Z, you can. It's decimal 26 or 0x1A.