How to print names on a multidimensional array in c++ - c++

I am trying to make a program to print the names of an array, the array represents the first row of the chess board. My attempt is with the following program but the only thing that I can achieve is printing numbers :( .
#include <iostream>
using namespace std;
void main()
enum pions // giving the names in pions
{
Tower=1 ,
Horse ,
Officer ,
Princes ,
King };
int Chess [0][8]={Tower , Horse , officer , Princes , King , Officer , Horse , Tower };
// putting the names of each coordinate in the array (above ) .
cout << " in this place the pion that is placed is the " << chess [0][1] << endl;
I know that the program will print the number 2 , but how can I make it print the word "Horse" instead of 2 ???
The cout command is written by the creator of the program (me :P) how i can give the option to the user to choose the part of the array that is going to be printed ?
Thanks in advance for your time and effort, a big sorry in case I am not clear, its my first post :D .
Any recommendations are welcome.

You need to write a function that takes a parameter of type Chess and returns a string. Here's one that would work:
const char *chessPieceName(Chess piece)
{
switch(piece) {
case Tower:
return "Tower";
break;
case Horse:
return "Horse";
break;
// etc.
default:
return "Not a valid piece";
break;
}
}
You can call then call this function from main:
cout << " in this place the pion that is placed is the " << chessPieceName(chess[0][1]) << endl;
Having said that, you have numerous other issues in your code that should prevent it from compiling. I'm not going to go through them, since you seem to just be interested in the question you asked.

You could have a translator function that takes the int value and transforms it into a printable string value:
string translate(int piecenum){
string [5] ref = { "Tower", "Horse", "Officer", "Princes" "King"}
return ref[piecenum];
}
You can print them out using cout << translate(chess[0][1]) << endl

You cannot print out identifiers of the enum.
You need to create a different function which takes your enum as an input parameter and returns an std::string with the name you want. For example, if you pass it pions::Tower, it will return "Tower". If you pass it pions::Horse, it will return "Horse". Etc.
Hint: Use a switch statement in the body of that function, as godel9's answer illustrates.

Either use C# instead of C++ or define yourself an array of chess figure names. For example
enum pions // giving the names in pions
{
Tower = 0 , // <== I prefer to use 0 instead of 1
Horse ,
Officer ,
Princes ,
King };
const char *name = { "Tower", "Horse", "Officer", "Princes", "King" };
//...
for ( int i : chess[0] ) std::cout << name[i] << std::endl;

Related

How to split strings and pass them to class vectors from file

For my university class in programming we have been working on Object Oriented Programming (OOP) and are currently working on a group project. The project is to create a cash register that holds items with their names, amounts, and prices. As well as have a way to track the coins given by the user then determine the coin denomination. These are supposed to be done in different classes and involve objects.
My question is regarding the inventory manager that I am coding. The inventory manager is supposed to take the "data.txt" file and read it into the appropriate vectors. Currently I have a vector for the item name, price, amount, and then the itemList vector which holds a string of all 3 to print to the user for readability.
Here is a snippet from the data file:
20 1.99 Potato Chips
10 5.99 Ibuprofen
4 1.42 Candy
55 3.10 Coffee
12 3.25 Hummus
12 4.55 Guacamole
7 0.80 Baklava
45 1.50 Chocolate Chip Cookies
My question is, how do I split the line up so that I can pass the amount (first number) to the appropriate vector, pass the price to the appropriate vector, then pass the name to the appropriate vector. Essentially splitting each line into 3 parts. The part that is the most difficult to me is how the names of the items can be 1 word, 2 words, or even 3 words. Making it difficult to predict how many spaces the name will have, which caused a lot of my attempts to not work.
I found a working solution though I'm worried it's incorrect or inefficient and I'm curious in knowing the best way to do this. Thank you so much ahead of time and I will post the class definition and the method I'm working in down below.
< The stream object is inFile>
class inventoryManager
{
private:
double total, change, choice;
vector <int> amount;
vector <string> name;
vector <double> price;
vector <string> itemList;
public:
void fileOpen(fstream& inFile);
void fillInventory(fstream& inFile);
void printInventory(fstream& inFile);
};
void inventoryManager::fillInventory(fstream& inFile)
{
string temp;
string a, b;
while (!inFile.eof())
{
inFile >> a >> b;
amount.push_back(stoi(a));
price.push_back(stod(b));
getline(inFile, temp);
name.push_back(temp);
itemList.push_back(temp);
}
}
Attempted: I tried using the find() function to find each space then use the index to print the estimated indices to each side of the white space to the vectors. Though it was extremely messy and wouldn't work if a different data file was inputted. The idea of the program is to be able to work if a different file is put in, similar format but the amount could be 100, and prices could be more digits. I also tried editing the file directly by adding new lines for each space but ran into the item names with multiple spaces and ultimately didn't work.
You are trying to do too many new things at once. Break the problem into pieces and solve them separately, then combine them. To break the string into pieces you can use find and substr, you just have to be careful and debug until you're sure it's working perfectly:
string s = "45 1.50 Chocolate Chip Cookies";
cout << "s: " << s << endl; // for debugging
size_t first = s.find(' ');
cout << first << endl; // for debugging
string amountString = s.substr(0, first);
cout << amountString << "X" << endl; // for debugging
size_t second = s.find(' ', first+1);
cout << second << endl; // for debugging
string priceString = s.substr(first+1,second-first-1);
cout << priceString << "X" << endl; // for debugging
string nameString = s.substr(second+1);
cout << nameString << "X" << endl; // for debugging
The purpose of those X's is to be certain that the substring has no trailing space.
Once you have tackled the problem this way (and handed the result in for a grade), you can advance to tools like stringstream, and you won't have to deal with this grubby index arithmetic any more.

How can i change colors in 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.

print called function name using GCC plugin

I need to print the name of the called functions of a program using gcc plugins
for this I created a pass that will be called after ssa pass, I already initiated the plugin and I can loop on its statements, using a gimple_stmt_iterator :
int read_calls(){
unsigned i;
const_tree str, op;
basic_block bb;
gimple stmt;
tree fnt;
FOR_EACH_BB_FN(bb, cfun) {
gimple_stmt_iterator gsi;
for (gsi=gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi))
{
stmt = gsi_stmt(gsi);
if (is_gimple_call(stmt)){
const char* name = THE_FUNCTION_I_NEED(stmt);
cerr << " Function : " << name << " is called \n";
}
}
}
return 0;
}
How can I print the name of the called function using its gimple node ??
Can I also print other informations like the line number where it was called, the name of the function where it was called etc .. ?
I've been looking for the answer for hours, the answer is actually pretty easy :
get_name(tree node)... I've been trying many functions since the documentation is really poor... I found it here :
GCC Middle and Back End API Reference
As you can see, there is no comments about what the functions does, and it quit the best documentation I found about gcc, anyway get_name(..) is working fine, bit I haven't find how to print the source line yet
I know three ways:
1:
tree current_fn_decl = gimple_call_fndecl(stmt);
const char* name = function_name(DECL_STRUCT_FUNCTION(current_fn_decl);
2:
const char* name = IDENTIFIER_POINTER(DECL_NAME(current_fn_decl));
3:
tree current_fn_decl = gimple_call_fndecl(stmt);
const char* name = get_name(current_fn_decl);

C++ Primer Plus Chapter 6 Exercise 2 Enter understanding

I am learning from C++ Primer Plus book, and I've recently done this exercise from the book. I have a problem: when the user hits enter without any sign, then in the next entry to display any of these functions he has to hit enter again, because if not it'll still display "Wrong choice" and "Next Choice:" all the time. Can you tell me what's wrong with this code, and what should I add?
Thanks in advance.
/*When you join the Benevolent Order of Programmers, you can be known at BOP
meetings by your real name, your job title, or your secret BOP name.Write a program
that can list members by real name, by job title, by secret name, or by a member’s
preference. Base the program on the following structure:
// Benevolent Order of Programmers name structure
struct bop {
char fullname[strsize]; // real name
char title[strsize]; // job title
char bopname[strsize]; // secret BOP name
int preference; // 0 = fullname, 1 = title, 2 = bopname
};
In the program, create a small array of such structures and initialize it to suitable
values. Have the program run a loop that lets the user select from different alternatives:
a. display by name b. display by title
c. display by bopname d. display by preference
q. quit
302 Chapter 6 Branching Statements and Logical Operators
Note that “display by preference” does not mean display the preference member; it
means display the member corresponding to the preference number. For instance, if
preference is 1, choice d would display the programmer’s job title.A sample run
may look something like the following:
Benevolent Order of Programmers Report
a. display by name b. display by title
c. display by bopname d. display by preference
q. quit
Enter your choice: a
Wimp Macho
Raki Rhodes
Celia Laiter
Hoppy Hipman
Pat Hand
Next choice: d
Wimp Macho
Junior Programmer
MIPS
Analyst Trainee
LOOPY
Next choice: q
Bye!*/
Solution:
#include <iostream>
void text();
void name();
void title();
void secret();
void prefr();
const int strSize = 23;
const int People = 4;
char ch;
struct bop {
char fullname[strSize]; // real name
char title[strSize]; // job title
char bopname[strSize]; //secret BOP name
int preference; // 0 = fullname, 1 = title, 2 = bopname
};
bop people[People] //array of 4 structures
{
{"Tony Hawk", "Junior Programmer", "Novice",2}, //first member
{"Bill Gates", "Founder of Microsoft", "Billionaire",1}, //second member
{"Pop Leather", "Graphic Designer", "Fast and Furious",2}, //third member
{"Steve Jobs", "Apple Leader", "Undead Dragon",0} //fourth member
};
int main()
{
text(); //call a text function
std::cin.get(ch); //get a character
int i=0;
while(ch!='q')
{
switch(ch)
{
case 'a':
name();
break;
case 'b':
title();
break;
case 'c':
secret();
break;
case 'd':
prefr();
break;
default: std::cout << "Wrong choice\n";
}
std::cout << "Next choice: \n";
std::cin.get();
std::cin.get(ch);
}
std::cout<<"Bye!";
return 0;
}
void text()
{
std::cout<<"Benevolent Order of Programmers Report\n"
"a. display by name b. display by title\n"
"c. display by bopname d. display by preference\n"
"q. quit\n"
"Enter your choice:";
}
void name()
{
for(int i=0;i<People;i++)
std::cout<<people[i].fullname<<std::endl;
}
void title()
{
for(int i=0;i<People;i++)
std::cout<<people[i].title<<std::endl;
}
void secret()
{
for(int i=0;i<People;i++)
std::cout<<people[i].bopname<<std::endl;
}
void prefr()
{
for(int i=0;i<People;i++)
{
if(people[i].preference==0)
std::cout<<people[i].fullname<<std::endl;
else if(people[i].preference==1)
std::cout<<people[i].title<<std::endl;
else if(people[i].preference==2)
std::cout<<people[i].bopname<<std::endl;
}
}
I think the problem lies here:
std::cin.get();
std::cin.get(ch);
If there was indeed a character, the first get will clean the newline, and the second will perform another read.
If there was no character to begin with, the first get will consume the actual input, and ch end up as a newline.
A solution to that is: don't treat input as valid if you're not sure it's valid. In particular, you're expecting two characters of input: any character except newline followed by newline.
There are two rather simple ways to solve your problem:
Don't use characters: simply work on std::string and treat empty string as invalid.
Check if the first character was a newline and don't skip an additional character then.
A more advanced solution would be to experiment more with functions. Could you wrap the input to return optional<char>? Or even better, optional<Choice>, where Choice is an enum class?
Or perhaps you could create a function that loops automatically, prompting for a proper input every time, and separate it from the main program logic?

Change the value of a variable in C++?

i hope you can help me.
The thing is that i don't know how to change the value of a variable, for example, i have a
"char" variable and then i wanna change it to "int" or "float"
This is the code
#include<iostream>
#include<cstdlib>
using namespace std;
main()
{
{
cout<<" El valor de las calificaciones es A=10,B=9,C=8,D=7,E=6,F=5,G=4,H=3,I=2,J=1 " <<endl;}
char calificaciones[4];
int resultado,A=10,B=9,C=8,D=7,E=6,F=5,G=4,H=3,I=2,J=1, i, promedio;
for(i=1;i<4;i++)
{
cout<<"Ingrese calificacion con letra "<<i;
cin>>calificaciones[i];
}
promedio=(calificaciones[1]+calificaciones[2]+calificaciones[3])/3;
cout<<"El promedio de sus tres calificaciones es "<<promedio<<endl;
system("pause");
}
The program is supposed to ask for the user to enter three scores and the scores are shown in letters as you can see, A=10, B=9, etc, and once the user enters three letters the program is going to divide them into three, but since the variable "calificaciones" was a string first, how do i make the operation i want to do this, or whats the command that i could use for the program to understand that the user entered three letters and an operation will be made with them?
Hope you can help me and thanks.
If your original question is, how to change datatype, sorry that is not possible.
Although, what you are trying to achieve can be done by std::map
Create Map of your grades.
std::map<char,int> myGrades;
myGrades.insert ( std::pair<char,int>('A',10) );
myGrades.insert ( std::pair<char,int>('B',9) );
myGrades.insert ( std::pair<char,int>('C',8) );
myGrades.insert ( std::pair<char,int>('D',7) );
Read input: (this is same. only change is index starts from 0)
for(i=0;i<3;i++)
{
cout<<"Ingrese calificacion con letra "<<i;
cin>>calificaciones[i];
}
Get actual integers from map.
int total_grades = ( myGrades.find(calificaciones[0])->second +
myGrades.find(calificaciones[1])->second +
myGrades.find(calificaciones[2])->second);
promedio=total_grades /3.0; //<-- NOtice 3.0 to avoid int/int
It's impossible to change the datatype of a variable in strongly-typed languages like C++, Java, etc. You'll need to define a new variable with the desired type instead. Weakly-typed languages like Python and PHP are (generally) typeless and will let you mix and match datatypes however you like, but it's not possible in C++. You can technically use void pointers to point to objects of any type, but they don't let you change the type of existing variables. Here is more information on strong and weak typing.
If you're okay with creating a new variable, you can use conversion functions or manually convert between datatypes (if possible). For example, it's not possible to convert the string "Hello world" to an int, but you can change a string like "42" to an int. The cstdlib / stdlib.h header provides functions like atof() and atoi() which can do basic conversions (make sure you convert any C++ strings to character arrays using myString.c_str() before passing them). stringstream is also a very powerful tool which easily converts practically anything to a string, among other uses.
I'm not quite sure what you want to do, but you can use the ASCII values of the characters to convert them. For example, the letter A has the ASCII value of 65, B is 66, C is 67, and so on. Because characters are inherently stored as numbers, you can convert them without using special conversion functions. You can simply assign a char to an int:
char ch = 'A';
int x = ch; // this is an implicit conversion
cout << x << endl; // this prints '65'
The character is being cast to an integer. You can also explicitly convert it:
char ch = 'A';
cout << ch << endl; // this prints 'A'
cout << (int) ch << endl; // this prints '65' because of the explicit conversion
It also works the other way around:
int x = 65;
char ch = x;
cout << ch << endl; // this prints 'A'