0

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;
}
4
Contributors
10
Replies
11
Views
5 Years
Discussion Span
Last Post by Ancient Dragon
Featured Replies
0

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

0

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.

0

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.

0

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! :)

0

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

Or by choosing an exit character and not looping forever.

0

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. :)

0

@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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.