I have searched countless forums and websites but I can't seem to find the answer. I'm trying to use SetConsoleTextAttribute but it only affects the text. How can I affect the whole screen like the command color 1f would? My code is:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <wincon.h>
using namespace std;
int main()
{
SetConsoleTitle("C++ CALCULATOR"); // Title of window
int x; // Decision
int a; // First Number
int b; // Second Number
int c; // Answer
HANDLE Con;
Con = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(Con, BACKGROUND_BLUE | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
cout << "CALCULATOR" << endl << endl;
cout << "1:ADDITION" << endl << "2:SUBTRACTION" << endl << "3:MULTIPLICATION";
cout << endl << "4:DIVISION" << endl << "5:EXIT" << endl;
cin >> x;
switch (x)
{
case 1: // Addition code
cout << endl << "ADDITION" << endl << "FIRST NUMBER:";
cin >> a;
cout << endl << "SECOND NUMBER:";
cin >> b;
c = a + b;
cout << endl << "ANSWER:" << c;
break;
case 2: // Subtraction code
cout << endl << "SUBTRACTION" << endl << "FIRST NUMBER:";
cin >> a;
cout << endl << "SECOND NUMBER:";
cin >> b;
c = a - b;
cout << endl << "ANSWER:" << c;
break;
case 3: // Multiplication code
cout << endl << "MULTIPLICATION" << endl << "FIRST NUMBER:";
cin >> a;
cout << endl << "SECOND NUMBER:";
cin >> b;
c = a * b;
cout << endl << "ANSWER:" << c;
break;
case 4: // Division code
cout << endl << "DIVISION" << endl << "FIRST NUMBER:";
cin >> a;
cout << endl << "SECOND NUMBER:";
cin >> b;
c = a / b;
cout << endl << "ANSWER:" << c;
break;
case 5: // Exit code
return 0;
}
}
This solution relies on these WinAPI functions and structures:
GetConsoleScreenBufferInfo to get screen dimensions
FillConsoleOutputAttribute to fill screen with an attribute
CONSOLE_SCREEN_BUFFER_INFO structure to store screen information
The code is as follows:
HANDLE hCon;
CONSOLE_SCREEN_BUFFER_INFO csbiScreenInfo;
COORD coordStart = { 0, 0 }; // Screen coordinate for upper left
DWORD dwNumWritten = 0; // Holds # of cells written to
// by FillConsoleOutputAttribute
DWORD dwScrSize;
WORD wAttributes = BACKGROUND_BLUE | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
// Get the screen buffer information including size and position of window
if (!GetConsoleScreenBufferInfo(hCon, &csbiScreenInfo))
{
// Put error handling here
return 1;
}
// Calculate number of cells on screen from screen size
dwScrSize = csbiScreenInfo.dwMaximumWindowSize.X * csbiScreenInfo.dwMaximumWindowSize.Y;
// Fill the screen with the specified attribute
FillConsoleOutputAttribute(hCon, wAttributes, dwScrSize, coordStart, &dwNumWritten);
// Set attribute for newly written text
SetConsoleTextAttribute(hCon, wAttributes);
The inline comments should be enough to understand the basics of what is going with the supplied documentation links. We get the screen size with GetConsoleScreenBufferInfo and use that to determine the number of cells on the screen to update with a new attribute using FillConsoleOutputAttribute . We then use SetConsoleTextAttribute to ensure that all new text that gets printed matches the attribute we used to color the entire console screen.
For brevity I have left off the error check for the calls to FillConsoleOutputAttribute and SetConsoleTextAttribute. I put a stub for the error handling for GetConsoleScreenBufferInfo . I leave it as an exercise for the original poster to add appropriate error handling if they so choose.
SetConsoleTextAttribute changes the attribute for new characters that you write to the console, but doesn't affect existing contents of the console.
If you want to change the attributes for existing characters already being displayed on the console, use WriteConsoleOutputAttribute instead.
Related
When I run it on the terminal it works fine but the loop. The for loop just doesn't do anything at all. I'm learning C++, so I don't know much.
#include <iostream>
#include <cstring>
using namespace std;
int main( int argc, char *argv[] ) {
if (argc == 2) {
cout << "The first argument is " << argv[0] << endl;
cout << "The second argument is " << argv[1] << endl;
} else if (argc > 2) {
cout << "Too many arguments" << endl;
exit(0);
} else {
cout << "Only one argument" << endl;
cout << "The argument is " << argv[0] << endl;
exit(0);
}
if (atoi(argv[1]) < 0) {
cout << "Error negative number" << endl;
exit(0);
}
// this loop does not work, everything else does.
for (int i = 1; i >= atoi(argv[1]); i++){
int count = atoi(argv[1]--);
cout << count << endl;
int sum = sum + i;
}
cout << "The sum is: " << endl;
return(0);}
I think that could be the if statements what are messing around with the loop.
I think you made mistake in the for loop.
You show use "<=" instead of ">=" in the for loop.
Hope this might helps you.
I guess your code is not reaching the for loop as you have exit() conditions on each and every condition of if. Your code only reaches the loop if you are passing 2 arguments in the terminal while you are running your code
I'm a beginner trying to figure out this program of adding fractions while also making their output print the result in it's lowest common denominator form. Running it in this form never runs properly...
using namespace std;
class Fraction { //Creates class Fraction
private: //Makes data members private
int num;
int denm;
};
int main()
{
int num;
int denm;
int num2;
int denm2;
int plus;
int plus2;
cout << "Please enter the numerator and denominator of the first fraction: " << endl;
cin >> num >> denm;
cout << "Please enter the numerator and denominator of the second fraction: " << endl;
cin >> num2 >> denm2;
plus = num*denm2 + denm*num2;
plus2 = denm*denm2;
cout << num << "/" << denm << " + " << num2 << "/" << denm2 << " = " << plus << "/" << plus2;
cout << "Hit 'enter' to exit..." << endl;
}
You'll need to run the program in a fashion that keeps the output window open or modify it to accomplish this. See here for examples:
How to keep the console window open in Visual C++?
One way to do this in any environment would be to cin another value before the final return 0 - this would, of course, require you to press something other than enter first, but it serves the purpose.
I have a map that represents the values of a coefficient Y for a given range of temperatures. I'm trying to get the coeff_Y whenever the input key designTempfalls anywhere between the upper and lower limits of keys. I was able to get the three cases: a) when the value of the input designTemp is below the first key then coeff_Y is the first value, b) if the value of the input designTemp is beyond the last key then coeff_Y is the last value and c) if designTemp matches a key then the coeff_Y becomes the corresponding value. The case if the key falls anywhere within the key range is not working. The code showing the failed attempt of interpolation is shown below. Please note that I'm not a programmer, I'm a piping engineer just trying to write my own programs and trying to become proficient at coding with C++. Also, if there is any better solution please show so.
`cout << "\n Enter design temp. in degF: ";
float designTemp;
cin.clear(); cin.ignore(10000, '\n'); cin >> designTemp;
map<float, float> ferriticsteels_Y = { {900, 0.4}, {950, 0.5}, {1000, 0.7} };
if (ferriticsteels_Y.find(designTemp) != ferriticsteels_Y.end())
{
float coeff_Y = ferriticsteels_Y[designTemp];
cout << "\n Y: " << coeff_Y << endl;
}
if (designTemp < ferriticsteels_Y.begin()->first)
{
float coeff_Y = ferriticsteels_Y.begin()->second;
cout << "\n Y: " << coeff_Y << endl;
}
if (designTemp > ferriticsteels_Y.rbegin()->first)
{
float coeff_Y = ferriticsteels_Y.rbegin()->second;
cout << "\n Y: " << coeff_Y << endl;
}
auto lower = ferriticsteels_Y.lower_bound(designTemp) == ferriticsteels_Y.begin() ? ferriticsteels_Y.begin() : --(ferriticsteels_Y.lower_bound(designTemp));
auto upper = ferriticsteels_Y.upper_bound(designTemp);
float coeff_Y = lower->second + (upper->second - lower->second) * float(designTemp - lower->first)/fabs(upper->first - lower->first);
time_t rawtime_end;
struct tm * timeinfo_end;
time(&rawtime_end);
timeinfo_end = localtime(&rawtime_end);
cout << "\n" << asctime(timeinfo_end);
cout << "\nEnter any character and hit enter to exit: ";
char ans;
//cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin >> ans;...giving error at 'max()'
cin.clear(); cin.ignore(10000, '\n'); cin >> ans;
return 0;}`
It works. I just was making stupid mistake. It only required to revise the nesting of the if-statements and to add a cout for looking the interpolated value at the last else. Below is the code which works as expected:
#include "../../std_lib_facilities.h"
#include <Windows.h>
#include <map>
int main()
{
SetConsoleTitle(TEXT("PipeTran™_v0.1"));
system("CLS");
system("color F1");
time_t rawtime_start;
struct tm * timeinfo_start;
time(&rawtime_start);
timeinfo_start = localtime(&rawtime_start);
printf(asctime(timeinfo_start));
cout << "\n Enter design temp. in degF: ";
float designTemp;
cin >> designTemp;
map<float, float> ferriticsteels_Y = { { 900, 0.4 },{ 950, 0.5 },{ 1000, 0.7 } };
if (ferriticsteels_Y.find(designTemp) != ferriticsteels_Y.end()) {
float coeff_Y = ferriticsteels_Y[designTemp];
cout << "\n Y: " << coeff_Y << endl;
}
else if (designTemp < ferriticsteels_Y.begin()->first) {
float coeff_Y = ferriticsteels_Y.begin()->second;
cout << "\n Y: " << coeff_Y << endl;
}
else if (designTemp > ferriticsteels_Y.rbegin()->first) {
float coeff_Y = ferriticsteels_Y.rbegin()->second;
cout << "\n Y: " << coeff_Y << endl;
}
else {
auto lower = ferriticsteels_Y.lower_bound(designTemp) == ferriticsteels_Y.begin() ? ferriticsteels_Y.begin() : --(ferriticsteels_Y.lower_bound(designTemp));
auto upper = ferriticsteels_Y.upper_bound(designTemp);
float coeff_Y = lower->second + (upper->second - lower->second) * float(designTemp - lower->first) / fabs(upper->first - lower->first);
cout << "\n Y: " << coeff_Y << endl;
}
time_t rawtime_end;
struct tm * timeinfo_end;
time(&rawtime_end);
timeinfo_end = localtime(&rawtime_end);
cout << "\n" << asctime(timeinfo_end);
cout << "\nEnter any character and hit enter to exit: ";
char ans;
cin.clear(); cin.ignore(10000, '\n'); cin >> ans;
return 0;
}
Using the Eigen C++ library, I have a Matrix3f A, a Vector4f b, and a Vector4f c. I want to create a Matrix4f M out of these. I want the top 3-by-3 corner of M to be A, I want to final column of M to be b, and I want the bottom row of M to be c.
I know how to do this by simply creating a Matrix4f and assigning each element individually. But is there a more elegant solution that Eigen supports?
Does this count as elegant enough?
#include <Eigen/Sparse>
#include <iostream>
using namespace Eigen;
using std::cout;
using std::endl;
int main(int argc, char *argv[])
{
Matrix4f m = Matrix4f::Random();
Matrix3f A = Matrix3f::Constant(0.1);
Vector4f b = Vector4f::Constant(0.2), c = Vector4f::Constant(0.3);
cout << m << endl << endl;
cout << A << endl << endl;
cout << b << endl << endl;
cout << c << endl << endl;
m.block(0, 0, 3, 3) = A;
m.col(3) = b;
m.row(3) = c;
cout << m << endl << endl;
return 0;
}
Note that your question is kinda ambiguous, as the (3,3) position will be determined by the order of assignment between b and c.
I have a small bit of code I made on Microsoft Visual studio that is a simple program I used to teach someone the fundamentals of C++. I am moving to Xcode and it is new to me. I need help reformatting this code so it can be run on a mac. Please help!
#include <iostream>
#include <string>
#include <random> //this needs to be included for the rand() function
#include <time.h> //this needs to be included for the seed time
#include <windows.h>
#include <conio.h>
using namespace std;
//PAB
int random_in_range(int a, int b)//this function will generate a random number between specified range
{
return (a+rand()%(b-a+1));
}
void hangman(){
char guess;
string word="";
string hidden ="";
int strikesLeft= 0;
int random = random_in_range(1,15);
switch(random){
case 1:
word = "bacon";
hidden ="?????";
strikesLeft=5;
break;
case 2:
word = "computer";
hidden ="????????";
strikesLeft=7;
break;
case 3:
word = "human";
hidden = "?????";
strikesLeft=7;
break;
case 4:
word = "desk";
hidden = "????";
strikesLeft=7;
break;
case 5:
word = "card";
hidden = "????";
strikesLeft=7;
break;
case 6:
word="keyboard";
hidden = "????????";
strikesLeft=7;
break;
case 7:
word="phone";
hidden="?????";
strikesLeft=7;
break;
case 8:
word="mouse";
hidden="?????";
strikesLeft=7;
break;
case 9:
word="camp";
hidden="????";
strikesLeft=7;
break;
case 10:
word="captain";
hidden="???????";
strikesLeft=7;
break;
case 11:
word="brother";
hidden="???????";
strikesLeft=7;
break;
case 12:
word="beauty";
hidden="??????";
strikesLeft=7;
break;
case 13:
word="cave";
hidden="????";
strikesLeft=7;
break;
case 14:
word="children";
hidden="????????";
strikesLeft=7;
break;
case 15:
word="action";
hidden="??????";
strikesLeft=7;
break;
}
bool gameOver=false;
int pos;
//add strike counter
cout << " ***WELCOME TO HANGMAN***" << endl << endl;
cout << "Try to guess the word in question marks. But watch out, if you use too many letters not in the word, you will lose." << endl;
cout << "You start with " << strikesLeft << " strikes." << endl;
cout << "Good luck..." << endl;
do{
cout << "Word is " << hidden << endl << endl;
cout << "Enter guess: ";
cin >> guess;
pos = word.find_first_of(guess);
if(pos!=-1)
hidden[pos]=guess;
else{
strikesLeft--;
cout <<"Sorry, " << guess << " is not in this word." << endl;
cout <<"You have " << strikesLeft << " strikes left." << endl; //also tell them strikes remaining
}
if(hidden==word || strikesLeft==0)
gameOver=true;
}
while(gameOver==false);
if(strikesLeft==0)
cout << "Game Over! You failed..." << endl;
cout << "The word was " << word << "." << endl;
if(strikesLeft>0)
cout << "Congrats! You completed my game with " << strikesLeft << " strikes left." << endl;
system("PAUSE");
}
int main(){
cout << "" << endl << endl << endl << endl << endl << endl << endl;
cout << " *WELCOME*" << endl;
system("color 0c");
Sleep(500);
cout << " **TO**" << endl;
system("color 0f");
Sleep(500);
cout << " ***PAB***";
system("color 0a");
Sleep(3000);
system("cls");
cout << "" << endl << endl << endl << endl << endl << endl << endl;
cout << " P";
Sleep(100);
cout << "E";
Sleep(100);
cout << "R";
Sleep(100);
cout << "S";
Sleep(100);
cout << "O";
Sleep(100);
cout << "N";
Sleep(100);
cout << "A";
Sleep(100);
cout << "L";
Sleep(1000);
cout << " A";
Sleep(100);
cout << "W";
Sleep(100);
cout << "E";
Sleep(100);
cout << "S";
Sleep(100);
cout << "O";
Sleep(100);
cout << "M";
Sleep(100);
cout << "E";
Sleep(1000);
cout << " B";
Sleep(150);
cout << "O";
Sleep(150);
cout << "T";
Sleep(2000);
system("cls");
system("color 08");
cout << "Program loading.";
Sleep(500);
system("cls");
cout << "Program loading..";
Sleep(500);
system("cls");
cout << "Program loading...";
Sleep(500);
system("cls");
cout << "Program loading.";
Sleep(500);
system("cls");
cout << "Program loading..";
Sleep(500);
system("cls");
cout << "Program loading...";
Sleep(500);
system("cls");
cout << "Program loading.";
Sleep(500);
system("cls");
cout << "Program loading..";
Sleep(500);
system("cls");
srand(time(NULL));//seeds the random number generator. Do this before calling the randomInRange function
string name;
int friends;
int DecimalArray[] = {1,2,3,4,5,22,555,85,18,741}; //Create an array of decimal numbers.
system ("color 0f");
cout << "Enter name: ";
cin >> name;
cout << "Hi " << name << "." << " My name is PAB, your personal awesome bot." << endl;
cout << "Now tell me, how many friends do you have? " << endl;
cin >> friends;
if(friends >=75 && friends <300)
cout << "Gee, " << friends << " friends is a lot. But you could always have one more...ME!!" << endl;
if(friends >300)
cout << "Yeah, maybe on Facebook...But we should still be friends!" << endl;
if(friends <75)
cout << "Man, you totally need more friends. I can be one of them!" << endl;
int randomNum=random_in_range(1,50);
int numGuess;
cout << "Now that we're friends, I want to play a game. Now, pick a number between 1 and 50. " << endl;
do{ //dowhile loop using "getting closer" for when your getting closer to the number
cin >> numGuess;
if(numGuess >50)
cout << "Can you read? It clearly says between 1 and 50. " << endl;
if(numGuess >randomNum)
cout << "That's too high guess again. " << endl;
if(numGuess <randomNum)
cout << "That's too low please guess again. " << endl;
}while(numGuess !=randomNum);
system("cls");
cout << "Congratulations! You found out my number." << endl;
cout << "Okay, I agree that was stupid. But, I have another game!" << endl << endl << endl;
hangman();
system("cls");
cout << "Thanks for playing with me today! I hope you had fun." << endl;
cout << "In the future I will have new games and jokes." << endl << endl << endl << endl << endl << endl;
cout << " THE END" << endl;
Sleep(5000);
system("cls");
system("color 08");
cout << "v1.7" << endl;
cout << "[copyright]" << endl;
cout << "Ethan MacCumber 2012" << endl;
system("PAUSE");
return 0;
}
Your major problem is that your code isn't entirely standard C++. You used C++ code that is only available on Windows, the functions in the windows.h and conio.h header files. Any functions in those header files won't work on a Mac.
If you want your code to run on Mac OS X, comment out the includes of windows.h and conio.h. Commenting out the includes of the Windows-specific headers will generate a ton of compiler errors, which should show you where the Windows-specific code is. Get rid of that code and stick with code that is standard C++, like cin and cout. From a quick glance at your code, the calls to Sleep() and System("cls") won't work on a Mac.