Question

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;
}
Was it helpful?

Solution

You are mixing Windows console I/O with C++ stream I/O. To paraphrase Gary Larson, you've mixed incompatible species in the terrarium.

Try using just C++ constructs, like this:

std::cout << "Enter name, age, GPA; or CTRL-Z to exit\n";
while ( cin >> name >> age >> GPA )
{
  // do something with one set of input
}

Or, if you want to keep your do-while format:

do
{   //enter student data
  cout << "Name:  " ;
  if( !cin>>name ) break;
  cout<<"Age:  ";
  if( !cin>>age) break;
  cout << "GPA:  ";
  if( !cin>>GPA) break;
}
while(cin);  //Ctrl+Z to exit

OTHER TIPS

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.

If you're using a unix derived compiler, try ctrl-D. I'm not very familiar with Dev-C++, but it says something about MinGW when I looked it up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top