For example, if I type 'a', how do I print out the value of the variable a, i.e. "0 1" ?
string a = "0 1"; string c = "1 1";
string b = "0 1"; string d = "1 1";
cin>>
cout <<
Are you sure you're not looking for a map?
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main(void) {
map<string, string> m;
m.insert(pair<string, string>("a", "0 1"));
m.insert(pair<string, string>("b", "0 1"));
m.insert(pair<string, string>("c", "1 1"));
m.insert(pair<string, string>("d", "1 1"));
string user_choice = "a";
cout << "Which letter?" << endl;
cin >> user_choice;
cout << "For " << user_choice << ": "
<< m.at(user_choice) << endl;
}
A std::map does exactly what it says. It maps values of one type to another, which is what it sounds like you're trying to do, and it does so without using variable names, which as others have pointed out, are discarded after compilation.
There are then all sorts of useful things that can be done to a map using the functions provided in the Standard Template Library.
You are asking about some kind of instrospection like some interpreted languages have, but C++ doesn't work that way.
This is not the right way to think about a C++ program (or in any other compiled language), the identifiers in the source code really disappear once the program is compiled.
In other words, there is no automatic relation between the character entered (e.g. "a") and the variable std::string a in the source code.
You have to manually do this:
#include<string>
int main(){
std::string a = "0 1";
std::string b = "0 1";
std::string c = "1 1";
std::string d = "1 1";
char x; std::cin >> x;
switch(x){
case 'a': std::cout << a << std::endl; break;
case 'b': std::cout << b << std::endl; break;
case 'c': std::cout << c << std::endl; break;
case 'd': std::cout << d << std::endl; break;
default: std::cout << "not such variable" << std::endl;
}
}
Related
I am having some trouble using a switch statement with user input. Can anyone please explain what is going on? I am sorry if this is a noob question as I'm very used to Python and just started learning C++.
#include <iostream>
#include <string>
using namespace std;
#include <cstdlib>
int main()
{
string name;
cout << "Enter a name: ";
cin >> name;
switch (name){
case name == "Seth":
std::cout << "That's my name!";
return 0;
break;
case name == "seth":
std::cout << "Wow, you couldnt even put correct capitalization on my name...\n";
std::cout << "LEARN YOUR PRONOUNS AND GO BACK TO SCHOOL!";
return 0;
break;
case name == "SETH":
std::cout << "Ok ok you spelled my name right but make sure you turn off caps lock please";
return 0;
break;
default:
std::cout << "Come on get my name RIGHT!!!\n";
std::cout << "But you entered " << name;
}
return 0;
}
According to the C++ 17 Standard (9.4.2 The switch statement)
2 The condition shall be of integral type, enumeration type, or class
type. If of class type, the condition is contextually implicitly
converted (Clause 7) to an integral or enumeration type. If the
(possibly converted) type is subject to integral promotions (7.6), the
condition is converted to the promoted type. Any statement within the
switch statement can be labeled with one or more case labels as
follows: case constant-expression : where the constant-expression
shall be a converted constant expression (8.20) of the adjusted type
of the switch condition. No two of the case constants in the same
switch shall have the same value after conversion.
The class std::string does not have an implicit conversion operator that converts an object of the type std::string to an integral or enumeration type.
So the expression in this switch statement
switch (name){
is invalid.
Also case labels like this
case name == "seth":
are syntactically incorrect.
You could resolve your problem with the switch statement for example the following way
#include <iostream>
#include <string>
#include <array>
#include <iterator>
#include <algorithm>
int main()
{
std::array<const char *, 3> names =
{
"Seth", "seth", "SETH"
};
std::string name;
std::cout << "Enter a name: ";
std::cin >> name;
size_t n = std::find( std::begin( names ), std::end( names ), name ) -
std::begin( names );
switch (n)
{
case 0:
std::cout << "That's my name!";
break;
case 1:
std::cout << "Wow, you couldnt even put correct capitalization on my name...\n";
std::cout << "LEARN YOUR PRONOUNS AND GO BACK TO SCHOOL!";
break;
case 2:
std::cout << "Ok ok you spelled my name right but make sure you turn off caps lock please";
break;
default:
std::cout << "Come on get my name RIGHT!!!\n";
std::cout << "But you entered " << name;
break;
}
}
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "Enter a name: ";
std::cin >> name;
if(name == "Seth")
{
std::cout << "That's my name!" << std::endl;
}
else if(name == "seth")
{
std::cout << "Wow, you couldn't even put correct capitalization on my name..." << std::endl;
std::cout << "LEARN YOUR PRONOUNS AND GO BACK TO SCHOOL!" << std::endl;
}
else if(name == "SETH")
{
std::cout << "Ok ok you spelled my name right but make sure you turn off caps lock please" << std::endl;
}
else
{
std::cout << "Come on get my name RIGHT!!!" << std::endl;
std::cout << "But you entered " << name << std::endl;
}
return 0;
}
As other people have told that you can not do string comparison in switch and provided a solution. But I would like to use enum class which I found more readable and int comparison much more faster than string comparison.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <unordered_map>
int main() {
enum class Spellings { Seth, seth, SETH };
const std::unordered_map<std::string, Spellings> spellings_map{
{"Seth", Spellings::Seth},
{"seth", Spellings::seth},
{"Seth", Spellings::SETH},
};
std::string name;
std::cout << "Enter a name: ";
std::cin >> name;
auto result = spellings_map.find(name);
if (result == spellings_map.end()) {
std::cout << "Come on get my name RIGHT!!!\n";
std::cout << "But you entered " << name;
return -1;
}
switch (result->second) {
case Spellings::Seth:
std::cout << "That's my name!";
break;
case Spellings::seth:
std::cout << "Wow, you couldnt even put correct capitalization on "
"my name...\n";
std::cout << "LEARN YOUR PRONOUNS AND GO BACK TO SCHOOL!";
break;
case Spellings::SETH:
std::cout << "Ok ok you spelled my name right but make sure you "
"turn off caps lock please";
break;
}
}
I'm (probably obviously) very new, and am attempting to build a calculator for my first project. I wanted to test my first concept, but upon compiling I get the 2059 error for the end brace of my InterFace struct as well as the first brace of my int AddUp. These seem like totally random errors. If it helps, the errors are for lines (10,1) and (16,2), although I suspect the 1 and 2 refer to number of like errors recorded? Any help would be appreciated.
1 #include <iostream>
2
3 struct InterFace
4 {
5 char Buttons[4][4]
6 {
7 Buttons[1] = "\u00B1";
8 std::cout << Buttons[1] << std::endl;
9 }
10 };
11
12
13 struct Addition
14 {
15 int AddUp[2]
16 {
17
18 }
19 };
int main()
{
std::cin.get();
}
You do not have the correct core concepts right, and should probably work through some C++ tutorials or courses before writing a program like this.
A few things:
The ± symbol is a unicode character. char in C++ refers to a single byte, usually an ASCII value if it's referring to text data. So it can't store the unicode +- symbol. Instead, you can store this unicode value in an std::string buttons[4][4]; (although the full answer is much more complicated).
In C++, 'a' refers to the character a, but "a" refers to a const char*. If it wasn't for the unicode issue, you should have used single quotes.
You try to assign to Buttons[1], but buttons is a 2-dimensional array. The element 1 also refers to the second element of the array, which may not be what you intended. Instead you could write Buttons[0][0]='a';
You don't have the concept of a member function/member variable down. The proper way to do this would be to have an initializer function and then call it.
Here is a fixed/working example, but I really recommend going through other tutorials first!
#include <iostream>
#include <string>
struct Interface {
std::string buttons[4][4];
void initialize_interface() {
buttons[0][0] = std::string("\u00B1");
std::cout << buttons[0][0] << std::endl;
}
};
int main() {
Interface my_interface;
my_interface.initialize_interface();
return 0;
}
As M.M. notes in the comments, a more paradigmatic approach would be the following:
#include
#include
struct Interface {
std::string buttons[4][4];
Interface() {
buttons[0][0] = std::string("\u00B1");
std::cout << buttons[0][0] << std::endl;
}
};
int main() {
Interface my_interface;
return 0;
}
Interface::Interface is called the constructor, and it runs upon initialization.
Since I wasn't able to build the calculator as I initially intended, I went a different route. I completed a basic one using switch instead.
#include <iostream>
int main()
{
int r;
int a;
int b;
int result1;
int result2;
int result3;
int result4;
int result5;
std::cout << "Please choose from the available options:" << std::endl << "0. Add" << std::endl << "1. Subtract" << std::endl << "2. Multiply" << std::endl << "3. Divide" << std::endl << "4. Modulo" << std::endl;
std::cin >> r;
switch (r % 5)
{
case 0:
std::cout << "You have chosen to Add, please enter two digits" << std::endl;
std::cin >> a;
std::cin >> b;
result1 = a + b;
std::cout << "Your sum is " << result1 << std::endl;
break;
case 1:
std::cout << "You have chosen to Subtract, please enter two digits" << std::endl;
std::cin >> a;
std::cin >> b;
result2 = a - b;
std::cout << "Your difference is " << result2 << std::endl;
break;
case 2:
std::cout << "You have chosen to Multiply, please enter two digits" << std::endl;
std::cin >> a;
std::cin >> b;
result3 = a * b;
std::cout << "Your product is " << result3 << std::endl;
break;
case 3:
std::cout << "You have chosen to Divide, please enter two digits" << std::endl;
std::cin >> a;
std::cin >> b;
result4 = a / b;
std::cout << "Your quotient is " << result4 << std::endl;
break;
case 4:
std::cout << "You have chosen to perform Modulus, please enter two digits" << std::endl;
std::cin >> a;
std::cin >> b;
result5 = a % b;
std::cout << "Your answer is " << result5 << std::endl;
break;
}
std::cin.get();
std::cin.get();
}
I am trying to make a text based C++ game.
I have a player class set up and I am now working on a method inside that class called displayMenu(), which will ask the user a variety of questions based on their player and send the data to the main/client code and then that data will create an object of player class via a constructor of player class.
My main question is...
I am trying to compare the input (string) from the user to the (string) they need to inputting, but I am getting an error which says "lower()" can not be resolved. I believe you have to compare each character, but I think there may be a more effective way to code this to provide simplicity and readability. What exactly am I doing wrong? What is the best way to code this?
Here is my code...
void Player::displayMenu(std::string& PlaName, std::string& cName, int& lvl, int& HP)
{
std::cout << "Player Creation Menu" << std::endl;
std::cout << "====================" << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << "What is your name? " << std::endl;
std::cin >> PlaName;
std::cout << "What is your specitality? " << std::endl;
std::cin >> cName;
while(cName.lower() != "brawler" || cName.lower() != "thief" || cName.lower() != "persuader" || cName.lower()
!= "gunman")
{
std::cout << "That is not your true specitality..." << std::endl;
std::cout << "You must pick from { 'Brawler', 'Thief' , 'Persuader', 'Gunman' }" << std::endl;
std::cin >> cName;
}
}
I have several remarks on your original code:
Reading and comparing the strings seems like a bit complicated for this use-case. It is common to see usage of first character as identifier, to make it simpler.
The specialty is a classic example for enum (or enum class, which is enum that you must use always with it's name)
The displayMenu method should not be part of the Player class, since it isn't a behavior (an action) of the player. It should be part of the "Game"/"UI" class.
If you really want to use the complete string in order to identify the specialty, you can use the code examples in the first answer in the link Ayxan put in the comments.
Here is my proposed code:
#include <iostream>
constexpr char INVALID_CHARACTER_INPUT = '#';
enum class CharacterSpecialty
{
BRAWLER,
THIEF,
PERSUADER,
GUNMAN,
NUM_OF_SPECIALITY_TYPES
};
`
class Player
{
public:
Player(const std::string& player_name, CharacterSpecialty char_specialty) :
name(player_name),
specialty(char_specialty)
{
}
private:
std::string name;
CharacterSpecialty specialty;
};
Player displayMenuAndCreatePlayer()
{
std::cout << "\nPlayer Creation Menu\n" << "====================\n\n" << std::endl;
std::cout << "Enter your name: " << std::endl;
std::string player_name{};
std::cin >> player_name;
CharacterSpecialty char_specialty = CharacterSpecialty::NUM_OF_SPECIALITY_TYPES;
while(char_specialty == CharacterSpecialty::NUM_OF_SPECIALITY_TYPES)
{
std::cout << "What is your specialty?\n" << "[B]rawler, [T]hief, [P]ersuader or [G]unman"<< std::endl;
std::string char_type_input;
std::cin >> char_type_input;
char input = char_type_input.size() == 1 ? char_type_input[0] : INVALID_CHARACTER_INPUT;
switch(char_type_input)
{
case 'b':
case 'B':
char_specialty = CharacterSpecialty::BRAWLER;
break;
case 't':
case 'T':
char_specialty = CharacterSpecialty::THIEF;
break;
case 'p':
case 'P':
char_specialty = CharacterSpecialty::PERSUADER;
break;
case 'g':
case 'G':
char_specialty = CharacterSpecialty::GUNMAN;
break;
default:
std::cout << "Invalid Specialty Entered!\n" << std::endl;
break;
}
}
return Player(player_name, char_specialty);
}
int main()
{
Player player = displayMenuAndCreatePlayer();
}
#include <iostream>
using namespace std;
void show_menu ()
{
cout << "Welcome" << endl;
cout << "1) Match line-up" << endl;
cout << "2) Match result" << endl;
cout << "3) Quit program" << endl;
}
int selection ()
{
cout << "Select option" << endl;
int input;
cin >> input;
return input;
}
int process (int x)
{
switch(x)
{
case 1:
cout << "Line ups" << endl;
case 2:
cout << "Arsenal 3 - Crystal Palace 0" << endl;
case 3:
cout << "Quitting" << endl;
default:
cout << "Select Option1" << endl;
}
}
int main ()
{
show_menu();
int input2 = selection ();
process(input2);
return 0;
}
So this is a code for some menu and input option, i wrote it as a exercise on subroutins, but in the function below i had a problem that i solved throgh some trile and arror, but still i dont get it.
int process (int x)
{
switch(x)
{
case 1:
cout << "Line ups" << endl;
case 2:
cout << "Arsenal 3 - Crystal Palace 0" << endl;
case 3:
cout << "Quitting" << endl;
default:
cout << "Select Option1" << endl;
}
}
Why do i need the variable (int x) in order dor this function to work?
i have a feel that i dont understand something very basic. pls help)
OK , so the function name is process (meaning you need to process something)
NOW , in order for your function to process something you need to give it that thing to be processed , right?
and the x variable which is an int data type ( int data type because it reflect the same value that was assigned inside your main method "input") is your argument that will be matched with the proper switch case as specified inside your process function.
one more thing , since you are not returning anything through your function , you don't need to declare it as an int , you only need to declare a data type for a function when you return the same data type , so in this case your function could be void.
hope this will help :)
The switch part checks whether the value of int x is 1,2,3 or default(something other than 1,2 and 3) and take the appropriate action(the different cout for each case).
There is no way for it to check the value of int x if you don't pass int x to the process function. I hope this makes things clear.
I have this (I've just started to learn btw):
#include <iostream>
#include <string>
using namespace std;
int main()
{
string mystr;
cout << "Welcome, what is your name? ";
getline(cin, mystr);
cout << "Nice to meet you, " << mystr << endl;
cout << "May i call you 1 for short? (y/n)" << endl;
getline(cin, mystr);
}
I want to next say;
cout << "Thank you, 1" << endl;
OR:
cout << "Well ok, " << mystr << endl;
... based on whether or not the user has typed y or n. How would i go about this? I've had a look around but i don't really know how to word it. I'm using Visual Studio Express and it is a console application.
For a very simple way:
if (mystr == "1") {
// ...
}
But you should accustom yourself to more error checking, so check the state of the stream after getline:
getline(cin, mystr);
if (cin) {
if (mystr == "1") {
// ...
}
} else {
// error
}
And of course, you may want to support any number in the future, not just 1. Then you need to convert the input string to a number. See std::stoi if you use C++11, or look at the thousands of past Stackoverflow questions about string-to-number conversions :)
Edit: Just noticed that you actually wanted to check for "y". Well, that's the same then:
if (mystr == "y") {
// ...
}
You should use if-else statement. For example
#include <cctype>
//...
std::string name = mystr;
std::cout << "May i call you 1 for short? (y/n)" << std::endl;
std::getline( std::cin, mystr );
for ( char &c : mystr ) c = std::tolower( c );
if ( mystr == "y" )
{
name = "1";
std::cout << "Thank you, " << name << std::endl;
}
else
{
std::cout << "Well ok, " << name << std::endl;
}