I'm just starting out in C++
Welcome! I know you will find learning to program C++ both confusing and enjoyable. May I suggest that you first acquire a good C++ book? There is an excellent list of such books here: The Definitive C++ Book Guide and List
1) What is wrong with the following program?
#include <iostream>
using namespace std;
You shouldn't import the entire std
namespace. There are a lot of symbols in that namespace, and you will almost certainly collide with one of them at some point. I know that many beginner textbooks instruct you to do this. Don't.
int main()
{
char thing[1];
There is no reason to declare thing
an array. It should be char thing;
.
cin >> thing;
Because, when you do this, you create a buffer-overflow bug. Since thing
is an array, cin
will treat thing
as a C-style string, and happily write the entire input line to it, even if it doesn't fit.
if (thing == 97)
cout << "You pressed 'a'!\n";
- (Assuming your didn't fix the definition of
thing
), thing==97
compares the array to the constant 97. More specifically, it compares the address of the first element of the array to the constant 97. This is a bad thing, and probably won't even compile.
- (Assuming you fixed the definition of
thing
), the naked constant 97
is confusing to the readers of your code, including to yourself. Instead compare thing
to the equally valid integral constant 'a'
.
Putting it all together:
#include <iostream>
using std::cout;
using std::cin;
int main()
{
char thing;
cin >> thing;
if (thing == 'a')
cout << "You pressed 'a'!\n";
else
cout << "You pressed not-'a': " << thing << "\n";
return 0;
}
2) How can I make it so that rather than having to type the letter as an input and press enter, the program just accepts the keypress immediately?
As others have pointed out, you must use a platform-specific API for this. On Microsoft Windows, try getch()
.