Hello, Beginner in C++

how to make this program if i pressed ctrl-c the program will quit.
and there's a tiny problem. whenever i run my program it says that return 0 is unreachable code. thanks guys :)

#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
while (1)
{
cout <<"Enter a character (ctrl-c to quit): ";
char input;
cin >>input;
cout <<input <<" is a ";
if (input >= 'a' && input <= 'z')
cout << "letter" <<endl;
else
cout << "number" <<endl;
}
return 0;
}

whenever i run it, it doesn't exit. It loops forever. I need ctrl-c to exit my program.

sorry, but how? i mean i don't want it to be whenever i put something it suddenly exit. do you have any ideas? i tried searching but i simply don't understand.

A common way to end the loop is with end-of-file:

#include <iostream>

int main()
{
    char ch;
    
    while (std::cin.get(ch))
        std::cout.put(ch);
        
    std::cout << "Done\n";
}

From the keyboard you can signal end-of-file (usually with Ctrl-Z or Ctrl-D depending on the OS). This will put cin in a failure state which will then cause the loop condition to fail. To exit a loop either the condition must be false, or you must explicitly exit with the break keyword.

thanks for your help Narue, but we haven't discuss std yet. and my compiler doesn't recognize namespace. I'll just stick to my old program. thanks! :)

A common way to end the loop is with end-of-file:

Or by choosing an exit character and not looping forever.

Or by choosing an exit character and not looping forever.

That's far more application-dependent than EOF, so rather than list a bunch of caveats, I just went with the simplest suggestion. :)

@detailer: what compiler are you using? If it doesn't recognize namespace then it may be Turbo C++?

The behavior of Ctrl+C is operating system dependent. With most MS-Windows compilers and console programs it causes the program to terminate immediately. On other operating systems Ctrl+C may do nothing at all. You can change that behavior but doing so may be above your current programming skills and knowledge.

You will be far better off taking either Narue's of WaltP's suggestions. Either will allow the program to continue executing after the loop terminates, while Ctrl+C will not.

This article has been dead for over six months. Start a new discussion instead.