c++- variables to system() - c++

I am working on a console program for Windows, and one of my settings is an option to change the console and text color.
I am using c++, so I can do something like system("color 07");, which will make the background black and the text white.
What I want to do is to present all 16 color options, and then let the user take his pick.
(Below is a portion of my code):
int a;
int b;
cout << "Please enter your background color." << endl;
cin >> a; //the user inputs 0
cout << "Please enter your text color." << endl;
cin >> b; //the user inputs 7
How to I pass the two variables to the system() call? I googled around, but all I could find were string to system(), which I do not want.
Also, I am very well aware of how evil system() is, so if anyone has other options other than system() that will do the same thing, that would be fine. But please do not tell me how evil system() is.
Thanks in advance!!

The system command takes a single const char* parameter. Therefore you just need to build a string for the command you wish to execute.
#include <iostream>
#include <sstream>
#include <string>
int main()
{
int backgroundColor;
std::cout << "Enter background color\n";
std::cin >> backgroundColor;
int foregroundColor;
std::cout << "Enter foreground color\n";
std::cin >> foregroundColor;
std::stringstream stream;
stream << "color " << backgroundColor << foregroundColor;
std::cout << "Command to execute: '" << stream.str() << "'\n";
::system(stream.str().c_str());
return 0;
}

This could be a simpler solution using C++ constructs.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
string bgClr,fgClr;
cin >> bgClr >> fgClr;
::system((bgClr+fgClr).c_str());
return EXIT_SUCCESS;
}

char command[500] = "";
sprintf(command, "color(%d, %d)", a, b);
int result = system(command);

Related

Why am I not getting the output from the program. Whenever I run my code it stop after taking the input? [duplicate]

This question already has answers here:
How do I pass a cin'd c style string to a function?
(2 answers)
Closed last year.
Here is my code I am expecting the output but I am not getting .It stop after taking the input
I am expecting the output if i give name Harsh
Your name is Harsh
#include <iostream>
#include <cstring>
using namespace std;
int main() {
cout << "Enter your name" << endl;
char *s;
cin >> s;
cout << "Your name is " << s;
return 0;
}
I have also tried with cin.getline(s,100);but still it is not working.
So I request to you to solve the problem and give me solution.
Your code has undefined behavior because you are not allocating any memory for s to point at. s is an uninitialized pointer.
Try this instead:
#include <iostream>
using namespace std;
int main(){
cout << "Enter your name" << endl;
char s[100];
cin >> s; // or: cin.getline(s,100);
cout << "Your name is " << s;
return 0;
}
Alternatively, you should use std::string instead, eg:
#include <iostream>
#include <string>
using namespace std;
int main(){
cout << "Enter your name" << endl;
string s;
cin >> s; // or: getline(cin,s);
cout << "Your name is " << s;
return 0;
}
s in your code is unallocated.
Since it is C++ we're talking about, you probably don't want to use pointers and memory allocation, and use std::string instead.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
cout << "Enter your name" << endl;
string s; // Instead of dealing with char* allocation and memory issues.
cin >> s;
cout << "Your name is " << s;
return 0;
}
you have done it correctly but the problem with output is because of the memory allocation.
You have to allocate memory and try to avoid the concept of a pointer in that. Instead
Use string s;
or
char s[50];

Using std::getline() to read a single line?

My goal is to prompt user to enter a message / sentence and then print it out on the screen, using getline(). The following is two different attempts I have tried out.
First Attempt:
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main(){
chat message[80];
cout << "\n what is your message today?" << endl;
cin.getline( message, 80); // Enter a line with a max of 79 characters.
if( strlen( message) > 0) // If string length is longer than 0.
{
for( int i=0; message[i] != '\0'; ++i)
cout << message[i] << ' ';
cout << endl;
}
}
Second Attempt:
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main(){
string a = "a string";
cout << "\n what is your message today?" << endl;
while(getline(cin,a))
cout << a;
cout<<endl
}
}
For the fist attempt, the code simply print out "what is your message today?" and quit. I do not have a chance to enter any string at all. For the second attempt, it keeps asking me enter the message. Each time, when I enter something with the "\n", it would display what I entered on the screen. I use control + c to interrupt the running process to make it stop.
EDIT: To clarify and explain on my side, I extract the first attempt from a longer code, which is as the following.
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
char header[] = "\n *** C Strings ***\n\n"; // define a c string
int main()
{
char hello[30] = "Hello ", name[20], message[80]; // define a c string hello, declare two other c strings name and message
string a="fivelength";
cout << header << "Your first name: ";
cin >> setw(20) >> name; // Enter a word.
strcat( hello, name); // Append the name.
cout << hello << endl;
cin.sync(); // No previous input.
cout << "\nWhat is the message for today?"
<< endl;
cin.getline( message, 80); // Enter a line with a max of 79 characters.
if( strlen( message) > 0) // If string length is longer than 0.
{
for( int i=0; message[i] != '\0'; ++i)
cout << message[i] << ' ';
cout << endl;
}
return 0;
}
For the above code, it does not give me a chance to enter a message on the screen. I will put it as another question.
You are overcomplicating this, you can simply use std::string, which is the de-facto C++ string, and call the method, without using a loop.
You don't need a loop, since you are not going to repeatedly read lines, but only want to read one line, so no loop is needed.
#include <iostream>
#include <string> // not cstring, which is the C string library
using namespace std;
int main(void)
{
string message; // it can be an empty string, no need to initialize it
cout << "What is your message today?" << endl;
getline(cin, message);
cout << message;
cout<<endl;
return 0;
}
Output (Input: "Hello Stack Overflow!"):
What is your message today?
Message: Hello Stack Overflow!
PS: As #fredLarson commented, if you change chat to char in your first example, it should work. However, that code has a lot of commonalities with C.

Choose among more .txt

I'm working on a project and I need to select a different .txt every time based on the input.
This is what I have:
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <fstream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
string hp, att, def, vel, spec;
string answer, monster;
do
{
cout << "Which Monster?: ";
cin >> monster;
cout << endl;
ifstream selection;
selection.open(monster+".txt");
selection.close();
cout << endl << "Again? ";
cin >> answer;
}
while (answer == "y");
cout << "Hello world!" << endl;
return 0;
}
I have to get the monster string and search the .txt with the same name.
If I type "Troll" it will search for the Troll.txt
Is there a way?
This is the error I get:
F:\GdR\Campagna 1\CalcoloStats\main.cpp|22|error: no matching function for call to 'std::basic_ifstream::open(std::__cxx11::basic_string)'|
Given that monster is a std::string, this expression:
monster + ".txt"
is also a std::string.
Since C++11, you can use this as an argument to ifstream's open function just fine. However, until then, you are stuck with a limitation of ifstream which is that it can only take a C-style string.
Fortunately, you can get a C-style string from a std::string using the c_str() member function.
So, either:
selection.open((monster + "txt").c_str());
Or get a modern compiler / switch out of legacy mode.
Thanks Lightness Races in Orbit, solved with C++11 Compiler flag

Weird output at the end of string in Ubuntu terminal

I was trying C++ in Ubuntu terminal. I am getting weird symbols at the end of strings.(This also happened in the past in Codeblocks for Ubuntu but everything worked fine in Codeblocks Windows).
Here is the code:
#include <iostream>
using namespace std;
int main()
{
char name[20];
cout << "\nEnter name: ";
cin.getline(name, 20);
cout << "\nHello ";
cout.write(name, 20);
return 0;
}
Output:
Enter name: Yash
Hello Yash�#��Fy
I have checked other threads with the same problem. All of them had assignment problems where the users did not add '\0' at the end. But here I am doing no such thing. Then why do I get these characters at the end?
cout.write(name, 20);
will (try to) write exactly 20 characters, it will not check for '\0'. You can check such things in your favorite reference.
If you really want to use a char[] for this, you should just write
cout << name;
That will check for the terminating character.
However, it would be better to just ditch the C-style strings and move to std::string instead:
int main () {
std::string name;
std::cout << "\nEnter name: ";
std::getline(std::cin, name);
std::cout << "\nHello ";
std::cout << name;
}
To understand this better, you're never initializing the char name to 0, and cout.write() does not check for null. One option is to initialize char name to 0s from the start:
#include <iostream>
using namespace std;
int main()
{
char name[20] = {0};
cout << "\nEnter name: ";
cin.getline(name, 20);
cout << "\nHello ";
cout.write(name, 20);
return 0;
}
#BaummitAugen's answer is the proper way to do this, though.

Is it possible to "prepare" input from cin?

In his answer, specifically in the linked Ideone example, #Nawaz shows how you can change the buffer object of cout to write to something else. This made me think of utilizing that to prepare input from cin, by filling its streambuf:
#include <iostream>
#include <sstream>
using namespace std;
int main(){
streambuf *coutbuf = cout.rdbuf(cin.rdbuf());
cout << "this goes to the input stream" << endl;
string s;
cin >> s;
cout.rdbuf(coutbuf);
cout << "after cour.rdbuf : " << s;
return 0;
}
But this doesn't quite work as expected, or in other words, it fails. :| cin still expects user input, instead of reading from the provided streambuf. Is there a way to make this work?
#include <iostream>
#include <sstream>
int main()
{
std::stringstream s("32 7.4");
std::cin.rdbuf(s.rdbuf());
int i;
double d;
if (std::cin >> i >> d)
std::cout << i << ' ' << d << '\n';
}
Disregard that question, while further investigating it, I made it work. What I did was actually the other way around than planned; I provided cin a streambuf to read from instead of filling its own.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
stringstream ss;
ss << "Here be prepared input for cin";
streambuf* cin_buf = cin.rdbuf(ss.rdbuf());
string s;
while(cin >> s){
cout << s << " ";
}
cin.rdbuf(cin_buf);
}
Though it would still be nice to see if it's possible to provide prepared input without having to change the cin streambuf directly, aka writing to its buffer directly instead of having it read from a different one.