How can i change colors in c++? - c++

So i searched for it and i found many answers. I found that in c++ there's no standard cross-platform way to do that and that the operative system manages colors. For example i found that on windows you can use the system("color 1") statement to change color to the text ( or foreground) and the system("color A") to change color to the background, or both system("color 1A") to change both. But this will change the whole colors, and i was wondering if there was a way to change it like even for a single character. Like take the program that i just did as an example:
#include<iostream>
using namespace std; /* I prefer to use this because i think that's a huge time saver and it's also easier*/
void printRoad(int i) /* That's my function, so by this function it prints a number of times choosed by the user 4 pieces of road*/
{
int counter=1;
while (counter <= i)
{
system("color 2"); /*Here is what i was talking about. I used the system("color 2") statement to change the text color
from the default to green, but it changes the whole text.*/
cout << "** | **" << endl;
cout << "** | **" << endl;
cout << "** | **" << endl;
cout << "** | **" << endl;
counter++;
}
};
void main() /*I don't need any specific return value from either the main() and the function so i thought it was a good idea to
just use void.*/
{
cout << "How many piece of roads do you want to build?" << endl; /*Here it asks to the user what to do.*/
int pieces = 0;
cin >> pieces;
printRoad(pieces); //Here is the function call.
system("pause"); /* Because i'm using windows and i'm using Visual Studio Express 2013 I used system("pause") to pause
the program and let the user see the output.*/
}
So what if, for example, i'd like to change each piece of road color? Like the first cout<<"** | **"<
I also read many people complaining about the use of system("") statements. I understand it because by doing so your program lose the cross-platform ability. But if the thing is dependent on the system we're on, how should we do it by keeping the cross-platform ability? Thanks for any answer.

Actually you can use this instead of calling system():
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), ValueOfColour);
As far as I understood your problem, you only want a certain character to be in your choosen colour. Then you need to change it back to the default value white/grey after this character was printed.

Related

trouble with loops, functions, and organization´

and I would like to preface this by saying this is NOT a current homework assignment; but it is an assignment from 3 years ago before I dropped out of school. I am self teaching and am revisiting an old assignment. I am NOT asking for the entire program, I'm simply looking for help building the skeleton for the initial start of the game.
MORE INFO:
Player 1 will enter word(of any length / i have been using "Testing") for Player 2 to guess. Player 2 will have 5 letter guesses, and 5 word guesses. If Player 2 enters "Testing" it should be able to ignore the case between upper/lower (WITHOUT using toupper / tolower)
IF: Player 2 enters more than 1 letter for a guess: "aa" make them guess again until they only guess 1 letter "a".
The problems I'm facing is: I don't know where to place everything, I feel I'm mixing up or messing up the functions, and everytime I try to organize it, it only gets worse. I've restarted it several times, I'm just having trouble getting it all laid out.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
string word, wordguess, lower, dashes;
string letterguess;
int i = 0;
bool GameOver = false, Validletterguess = true, Validwordguess = true;
cout << "Player 1, enter a word for Player 2 to guess: " << endl;
getline(cin, word);
cout << endl;
cout << "Player 2, you have 5 letter guesses, and 5 word guesses." << endl;
cout << "Guess your first letter: " << endl;
while (GameOver == false) // Start of Game. Setup for Round 1 letter guess and word guess.
{
while (letterguess.length() != 1) // 1 letter only. loop until they enter 1 letter
{
cout << endl << "Type a single letter and press <enter>: ";
cin >> letterguess; // enter letter guess
for (int i = 0; i < letterguess.length(); i++) //ignore case of letter guess
{
if (letterguess.at(i) >= 'A' && letterguess.at(i) <= 'Z')
{
lower += letterguess.at(i) + 32;
}
else
{
lower += letterguess.at(i);
}
}
if (letterguess.at(i) == word.at(i) && Validletterguess == true) //if Player2 guesses a correct letter, replace the dash with letter and display location: ex. If "T" then "You guessed the 1st and 4th letter"
{
cout << "You guessed the first letter right!" << endl; // figure out how to display dashes?
dashes.at(i) = letterguess.at(i);
cout << "Enter your first word guess: " << endl;
cin >> wordguess;
}
else
cout << "Wrong letter! Enter your first word guess: " << endl;
cin >> wordguess;
if (wordguess == word & Validwordguess = true)
{
cout << "You guessed the word correctly in 1 try! " << endl;
Gameover = true;
}
}
}
}
There are several things in C++ that can assist you. It's good to see that you're already using std::string and std::getline to deal with the user input. The problem seems to be that you've gotten tangled up in organizing the game logic so that it flows, and setting up structures that can help you.
I did actually go ahead and write a game just for kicks. The hope is that I can provide some of that and describe it so you can digest in chunks, and you can see how one can build a program up a bit at a time.
So let's start by making a stub for the function that will actually run the game. You can call this from main. It simplifies the actual running of the game by separating it from the other setup and shutdown stuff. It also means you can run several games in a row later, without having to modify the game loop.
enum GameResult {
None,
Win,
Loss,
};
GameResult PlayHangman(const std::string& target, int wrongLetterLimit, int wrongWordLimit)
{
return None;
}
And to illustrate that point, here is the full main that I ended up writing to invoke this game. Even though it's a one-off, you can see that it can be useful. In this case, I chose to read the game settings from the command line:
void ExitSyntaxMessage(int code = -1)
{
std::cerr << "Syntax: hangman <word> [guesses [wordGuesses]]\n";
exit(code);
}
int main(int argc, char** argv)
{
// Get game settings
std::string target;
int letterGuesses = 5;
int wordGuesses = 5;
try {
if (argc < 2) throw std::runtime_error("Not enough arguments");
target = argv[1];
if (argc > 2) letterGuesses = std::stoi(argv[2]);
if (argc > 3) wordGuesses = std::stoi(argv[3]);
}
catch(...)
{
ExitSyntaxMessage();
}
// Play game
GameResult result = PlayHangman(target, letterGuesses, wordGuesses);
// Deliver result and exit
switch(result)
{
case Win:
std::cout << "Congratulations!\n";
return 0;
case Loss:
std::cout << "Better luck next time!\n";
return 1;
default:
std::cout << "Game stopped.\n";
return -2;
}
}
So, now there's a simple framework for your game to run in. There's not much code, but it's something you can immediately start testing before moving on to fleshing out the game itself.
At this point, I should mention some headers that this program will be needing. Some will have been required already. Others are required for stuff we're about to do.
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
#include <set>
On to the game... A helper function to turn a string into lowercase is always handy. We'll definitely make use of that. Note that this uses a lambda function. If you don't have a modern C++ compiler (with C++11 support) you can just use an ordinary function pointer instead.
std::string Lowercase(const std::string& s)
{
std::string lc(s);
std::transform(lc.begin(), lc.end(), lc.begin(),
[](char c)->char{ return std::tolower(c); });
return lc;
}
Now it's time to expand on the PlayHangman stub. It's still gonna be a stub, but we can set up a few things that we'll be needing and get those tested before proceeding.
GameResult PlayHangman(const std::string& target, int wrongLetterLimit, int wrongWordLimit)
{
GameResult result = None;
// Create lowercase target and add its characters to set of remaining letters
std::string lcTarget = Lowercase(target);
std::set<char> lettersRemaining(lcTarget.begin(), lcTarget.end());
std::set<std::string> guesses;
// Set up game parameters
int letterGuessesRemaining = wrongLetterLimit;
int wordGuessesRemaining = wrongWordLimit;
// Sanity-test to ensure game is winnable
if (wordGuessesRemaining == 0 && letterGuessesRemaining < lettersRemaining.size())
{
std::cout << "Game is not winnable...\n";
return None;
}
// Game loop until stream error or game finishes
bool done = false;
while (!done)
{
done = true; // The loop is a stub for now
}
//// ^^^ for now, just use this bit to test the game setup stuff.
//// Make sure that your lowercase bits are working and the set of
//// remaining letters works. You can add some output code to debug
//// their values and run tests from the command line to verify.
return result;
}
That is going to be the primary structure of a single game. So let's talk about it. Notice again how I'm still not going into detail. At this point, I've already thought about how I should logically be running the game.
Now, I should say that in reality, most people don't write code in a linear way like this from the outside in. It's more of an organic process, but I do take care to separate stuff out into logical bits, and reshuffle/organize stuff as I go. I also try not to do too much at once.
You'll see by the way I've presented this, that I'm encouraging you to develop a solid platform in which to write your game logic. By the time you're writing that logic, you should be able to trust that everything else already works because you tested it.
Some things happening up there are:
The target string is copied into a lowercase version of itself. This will be used to test the word-guesses. There are other ways to test strings ignoring case, but this is just a simple way.
Because we've built that string, we can also use it to construct a std::set containing exactly one of each unique character in that string. That's a one-liner, constructing the set from the string's iterators. Very neat and tidy!
We also have a set of strings called guesses -- this will track all the guesses (correct/incorrect inclusive) so that you don't get penalized for accidentally repeating something you already guessed.
There's a sanity check, which is a duplicate of what will eventually be the end-game test inside the loop. To be honest, that was one of the last things I added, but I've put it here because it's part of the pre-game setup, and apart from the stubbed loop, this is the entire "game" sequence.
Checkpoint : Game skeleton complete
At this point, you might have seen enough to go off and complete the game. There are some important concepts introduced up there. In particular, the idea of storing the remaining letters as a std::set might be just the kind of trick that makes everything click into place.
Reading from here on will complete the program. It's up to you whether you want to do that, or stop reading and have a crack at it yourself first.
Let's start fleshing out some of the game loop. First, you probably wanna deal with showing the current game state and requesting input. That happens in two steps. The first part builds a string by hiding characters that are not yet guessed and then outputs it. The second part is an input-validating loop that discards empty lines, ignores duplicate guesses and handles end-of-stream.
Note that the input is converted to lowercase. This just simplifies things. Especially when checking for duplicate guesses.
while (!done)
{
// Create prompt from original string with a dash for each hidden character
std::string prompt(target);
for(char& c : prompt)
{
if (lettersRemaining.count(std::tolower(c)) != 0) c = '-';
}
std::cout << prompt << "\n";
// Get input
std::string input;
for (bool validInput = false; !validInput && !done; )
{
std::cout << "> " << std::flush;
if (!std::getline(std::cin, input))
{
done = true;
}
else if (!input.empty())
{
input = Lowercase(input);
validInput = guesses.insert(input).second;
if (!validInput)
{
std::cout << "You already guessed that!\n";
}
}
}
if (done)
continue;
// TODO: Process guess, update game state, and check end-game conditions
}
Once again, we have expanded on the implementation and now have something to test. So make sure it all compiles and works the way you want it to. Obviously the game will run forever right now, but that's fine -- you can just terminate the process.
When you're happy, move on to the actual logic. This is where we start putting together everything that has already been set up.
Thanks to our input loop, we now know that the input is now a new guess comprising either 1 letter or a word. So I start by branching for either the letter guess or the word guess. You should start to see a pattern here, right? Once again, I write an empty section of code to do something, and then start actually filling it in...
// Check the guessed letter or word
bool correctGuess = false;
if (input.size() == 1)
{
if (letterGuessesRemaining == 0)
{
std::cout << "No more letter guesses remain.\n";
}
else
{
// Test the guessed letter
}
}
else
{
if (wordGuessesRemaining == 0)
{
std::cout << "No more word guesses remain.\n";
}
else
{
// Test the guessed word
}
}
So, the letter test... Recall we already built the lettersRemaining set and tested it. And those are the only ones obscured by dashes in the prompt. So it then becomes trivial to determine whether they guessed one. If it's in the set, they guessed correctly and you remove it from the set. Otherwise, they burn up one of their guesses.
Because the input is already lowercase, we can use the letter verbatim to search within the values stored in the set (which are also lowercase).
// Test the guessed letter
char letter = input[0];
if (lettersRemaining.count(letter) != 0)
{
correctGuess = true;
lettersRemaining.erase(letter);
}
else
{
std::cout << "Nope!\n";
--letterGuessesRemaining;
}
The word test is even easier. Recall that we stored a lowercase version of the target word already, and the input was also converted to lowercase. So we just compare. You see how all this lowercase business has actually made life less complicated?
// Test the guessed word
if (input == lcTarget)
{
correctGuess = true;
lettersRemaining.clear(); //<-- we can use this to test for a win
}
else
{
std::cout << "Nope!\n";
--wordGuessesRemaining;
}
We are quite literally almost done! The only thing left to do is check whether the game should stop due to being won or lost. That's the last part of the game loop.
Because the code handling a correct word guess is also polite and clears the lettersRemaining set, we can use that as a test for a winning condition regardless of whether a letter or word was guessed.
You'll also see that bit of logic again for the game losing condition. Recall that from before the main loop where we checked if it was even possible to win.
// If guessed incorrectly, show remaining attempts
if (!correctGuess)
{
std::cout << "\nAttempts remaining: "
<< letterGuessesRemaining << " letters, "
<< wordGuessesRemaining << " words.\n";
}
// Check if game is complete
if (lettersRemaining.empty())
{
std::cout << target << "\n";
result = Win;
done = true;
}
else if (wordGuessesRemaining == 0 && letterGuessesRemaining < lettersRemaining.size())
{
std::cout << target << "\n";
result = Loss;
done = true;
}
I hope this has been helpful, that you've been able to follow along, and that you understand the breakdown and explanation. This is generally how I approach programming. I like to build up pieces of code that I can rely on, instead of getting lost in some details and overlooking more fundamental things.
There may be some techniques, language features or parts of the standard library used here that you have not encountered before. That's fine -- you can use that to learn, experiment and research online. Keep https://cppreference.com bookmarked in your browser.
If nothing else, I hope that this gives you some insight in breaking down tasks into small bits that you care about now, and other stuff that you can worry about later. Building up a program iteratively this way enables you to test code regularly and increases your chances of finding silly mistakes that could hamstring you later. It is so common to see beginners just write a whole program in one hit, run it, then freak out because it doesn't "work".

Creating a presentation in c++ ( I'm stuck ) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm working on a school project (I'm in seventh grade) and it's about why I want to be a computer programmer. I have to make a presentation of sorts about what a computer programmer is and what they do. I thought it would be a good idea to code my own presentation in a way. I've coded some of it already but i'm stuck. This is what I have so far,
#include <iostream>
#include <string>
using namespace std;
int main()
{
string question;
cout << "Type [1] to begin...";
cin >> question;
if(question == "1")
{
cout << "A computer programmer figures out the process of
designing, writing, testing, debugging, and maintaining the source c
ode for computer programs";
return 0;
}
}
Now what i want to be able to do is add a "goto" type of statement where it can go to something like "int second()" and cout something new like "what are programming languages?" and then a description of what they are after the user inputs something like "yes". Any help would be appreciated. I'm really new to c++. Thanks :)
I think this question is more suited for codereview, but since the code does not compile as is, we may as well help you with your broken code (and then you take it to codereview)
First, let's format your code. This is a useful skill to learn because it helps other coders help you write better code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string question;
cout << "Type [1] to begin...";
cin >> question;
if(question == "1") {
cout << "A computer programmer figures out the process of
designing, writing, testing, debugging, and maintaining the source c
ode for computer programs";
return 0;
}
}
Easiest way to format is to copy it into an IDE, use the IDE to format, then copy it back here, select the code and press the button.
Now to solve this problem.
Your question seems centred around controlling the flow of the program - being able to transition from one stage to the next in a way that puts the user in control and only delegates control back to your program once the user has made a decision.
The problem
Ask the user to enter a 1
Display the following text
A computer programmer figures out the process of designing, writing,
testing, debugging, and maintaining the source code for computer
programs
Ask the user if they wanted to continue
If so, display the following:
what are programming languages?
4b. If not, end the program.
Ask the user if they wanted to continue
etc, etc
As you can see, there is indeed a pattern and this pattern comes down to the following:
Ask what the user wants to do
Do it
Repeat until you run out of slides or the user doesn't want to continue
And just like that, we have abstracted away the complexity and are only focused on following the pattern.
Pay attention to the repeat part because that is what allows this pattern to work for more than one slide of your presentation. There are many ways to represent the repeat part, and for that you should find some good tutorials to teach you some of them. I won't bother describing all of them (just search youtube, you will find tons), but for this particular problem, the best way to represent your pattern is with a do-while loop.
Here is what it will look like:
do {
// Ask the user a question
// Get the user's input
// validate the user's input
// if they want to see the slide show it
// other wise, leave this loop
while (I have not run out of slides);
This is psuedo-code, but here is how it transforms your code:
#include <iostream>// cin, cout
#include <string> // string
#include <vector> // vector
#include <cstddef> // size_t
using namespace std;
int main() {
vector<string> slides = {
"A computer programmer figures out the process of"
"designing, writing, testing, debugging, and maintaining the source c"
"ode for computer programs",
"what are programming languages?",
// Add more here
};
size_t current_slide_index = 0;
string user_response;
do {
cout << "Type [1] to continue: ";
cin >> user_response;
cin.ignore(100, '\n'); // This is used to skip to the next line
if (user_response == "1") {
cout << slides.at(current_slide_index) << std::endl;
} else {
break;
}
} while (++current_slide_index < slides.size());
cout << "Happy learning\n";
return 0;
}
A few notes
I used a vector to hold the slides. This is the most recommended collection type in C++. There are many others, but for the most part, a vector will serve you well.
cin >> does not normally go to the next line after reading something, so I had to manually shift it to the next line. That's the reason for cin.ignore(100, '\n');
As I said in the beginning, this question is more suited for codereview, so take what I've shown you here, make your changes as you learn more about it, and later on have it reviewed once again by the folks at https://codereview.stackexchange.com/.
I think you can try a pattern like this:
#include <iostream>
#include <string>
using namespace std;
void q1()
{
cout << "A computer programmer figures out the process of "
"designing, writing, testing, debugging, and maintaining the source "
"code for computer programs.\n";
}
void q2()
{
cout << "what are programming languages? ...\n";
}
// void q3() ... ... ...
int main()
{
string question = "1";
cout << "Type [1] to begin... ([99] for quiting): ";
cin >> question;
/* while loop: http://en.cppreference.com/w/cpp/language/while */
while (question != "99") {
/* if statement: http://en.cppreference.com/w/cpp/language/if */
if (question == "1") {
q1(); // this is a "function call", you are invoking q1()
}
else if (question == "2") {
q2();
}
// else if(... q3() ... q4() ... and so on.
/* read a new response for checking in the while condition */
cout << "Next? ";
cin >> question;
}
return 0;
}
Using the the goto can be accomplished as below. You can also use the SWITCH..CASE to accomplish the same.
int main()
{
string question;
label:
cout << "Type [1,2,....] to begin...";
cin >> question;
if(question == "1")
{
cout << "A computer programmer figures out the process of designing, writing, testing, debugging, and maintaining the source code for computer programs" << endl;
goto label;
}
if(question == "2")
{
cout << " A programming language is a type of written language that tells computers what to do in order to work" << endl;
}
First of all it's fantastic that you want to be a programmer and I wish you luck on your assignment. You can certainly ask about learning c++ here, but this site is focused on question and answer, not on teaching. You have a pretty specific question here, but it can be solved in a broad variety of ways, which I'm sure you'll learn about soon.
What I would recommend for a presentation is to ignore the input so you don't have as many branches in your code. Then you can simply add the next part directly after the first.
string question;
cout << "Type [1] to begin...";
cin >> question;
cout << "A computer programmer figures out the process of
designing, writing, testing, debugging, and maintaining the source c
ode for computer programs";
cout << "Type [1] to continue...";
cin >> question;
cout << "Part 2";
return 0;
On the language choice:
C++ is definitely the wrong language to start. Because it's the most complicated programming language in existence(it's not an opinion, it's Science). You can't fully understand C++ without understanding other subset languages it contains. For example, C.
Don't listen to people that say you can code without complete understanding. You'll waste your time and won't become real engineer.
C is most stable and continuously respected programming language in Human History. Most modern CS celebrities like Mark Zucker., etc, started with C.
C can look as impressive as C++, if that's what you're interested in.
On the problem:
What you're doing is console dialog with finite determined input. In CS it's called "finite automata" or "state machine". State machine can be represented as a bunch of circles(states) and arrows between them: "Do this if the next input is that". Pick a starting circle and the end circle. i.e. your program terminates when it gets there. Such diagram are really that simple.
Step-by-step solution(fill in blanks):
0)Define IO.
Your input: 1 integer:
int input;
Your output: const strings of characters.
1) Draw state machine diagram, with states and arrows between them. Denote each arrow as Integer, output_string.
For example, '1, "A computer programmer figures.."' - is an arrow from the starting state (0) to some other state (1).
2) Create integer for states:
int state = 0;
3) Translate your state machine into diagram as following:(You don't need goto's. Loop can play as a goto)
while(scanf("%d", &input)){
switch(state){
case 0:
switch(input){
case 1:
printf("A programmer blabla\n");
state = 2;
break;
case 2:
...
{
break;
case 1:
...
case 10: // - last state
switch(input){
...
default:
printf("goodbye");
return 0; // terminate the program;
}
}
}
You need to know about while loops, Switch statements, printf() and scanf(). Wikipedia is ok.
After you did this put the code inside main function and make necessary includes and you're good to go. You need to complete your homework yourself.

Setting individual text colors in c++

I'm a beginner in C++ programming and I want to know how to set a text color for individual texts. I know how to set text colors using system("COLOR ..") but it applies color to ALL texts, not individual texts. There's a program I've been coding wherein when the text is "Yes" that "Yes" will be color green and when it is "No", that "No" will be color red. This is for console application.
cout<<"Available: ";
if(available == true){
//code for setting text colors to GREEN
}
else{
//code for setting text colors to RED
}
cout<<yesno;
//code for setting text colors back to WHITE
so the output will be like for example
Available: (textcolor="green")Yes(/textcolor)
Thank you for any help!
In addition to the existing answers, if you need a portable way of doing it and hide setting colors behind an API. There's a single header library rlutil, which does that for you, wrapping ANSI and Windows color and other console manipulations:
rlutil::setColor(rlutil::GREY)
You need to print your text using ANSI colour codes; but not all terminals support this - if colour sequences are not supported, garbage will show up.
Here is and example:
cout << "\033[1;31mbold red text\033[0m\n";
Here, \033 is the ESC character, ASCII 27. Followed by [, then one or two numbers separated by ;, and finally the letter m. See this table on Wikipedia for details.
Under Linux, you can do something like this:
#include <iostream>
using namespace std;
int main() {
cout << "\033[1;30mblack" << endl
<< "\033[1;31mred" << endl
<< "\033[1;32mgreen" << endl
<< "\033[1;33myellow" << endl
<< "\033[1;34mblue" << endl
<< "\033[1;35mmagenta" << endl
<< "\033[0mback to normal" << endl;
return 0;
}
Check this wiki for color table.
Under Windows, you can use SetConsoleTextAttribute, like this:
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE);
Check this page for all the character attributes.

Making a text box in c++

I'm programming some very simple stuff and I want to make a neat little "text box" at the beginning of my program in the command prompt with some basic info. An example of what I mean:
cout << "Creators: J. Adams & T. Jefferson" << endl;
cout << "Nicknames: Johnnny & Tommy" << endl;
cout << "Age: 20 & 21" << endl;
cout << "This program is for ..... << endl;
This is just an example, and one of the things I'd like is a simple way to align these things (so that "Johnny" is directly below "J. Adams", or at least directly enough so you know they belong together). I know of setw but you have to include for that, and I'd like a method where you don't have to use that.
Other than that, I'd like a simple way to put an outline around the text (that's what I mean by text "box"). Nothing to fancy, just something you can do with the first 128 normal characters. I've googled around for something similar to no avail.

Repeating loop until enter is pressed

For anybody else finding this question, this can be accomplished with the kbhit() function in the conio.h library. Just insert !kbhit() where I put SOMETHING and it will loop correctly, I am looking for a way to do this without a library, however.
I'm a beginner trying to create a simple animation in the console. The animation would have the word UP going up the right hand of the console and the word DOWN going down the right hand side. So far I have gotten the animation to complete one iteration of this, but I'm trying to make it so that it repeats and it looks like the texts wraps back to the top or bottom and does it again until the user presses the ENTER key.
My book (I'm self teaching from a textbook) makes it seem that its possible without any specific libraries except for iostream and windows.h but help that includes library functions is welcome too, it is a learning experience after all. Thanks a ton!
A little explanation of the code would be that I set the coordinates of the UP and DOWN starting positions and then move the cursor, delete the previous line it was on with a space and then increment two and put a new word. I would guess that I could use a second while loop to somehow check if the ENTER key has been pressed.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
COORD upPos = {20,28};
COORD downPos = {50, 0};
char endState;
while ( SOMETHING )
{
COORD upPos = {20,28};
COORD downPos = {50, 0};
while (upPos.Y >=0)
{
SetConsoleCursorPosition(screen,upPos);
cout << "UP" << endl;
upPos.Y++;
SetConsoleCursorPosition(screen,upPos);
cout << " " << endl;
upPos.Y -=2;
SetConsoleCursorPosition(screen,downPos);
cout << "DOWN" << endl;
downPos.Y--;
SetConsoleCursorPosition(screen,downPos);
cout << " " << endl;
downPos.Y+=2;
Sleep(100);
}
}
}
Your best bet is to create a custom "GetAsyncKeyState" function that will use #IFDEF for windows and linux to choose the appropriate GetAsyncKeyState() or equivalent. For ex
if (GetAsyncKeyState(VK_RETURN))
{
exit = true;
}