C++ - Boolean operation - c++

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;
}

Related

C++ Console Application, Outputting Incorrect Data

I've been working on a simple console application and was stopped when, upon compiling my latest code, it began outputting strings of text and integers which did not match what I have entered.
The purpose of the program thus far is simple: to input a string of data and for it to output correctly multiple times in the console application. Below I have linked the pseudocode.
Thanks in advance.
#include <iostream>
#include <string>
void printIntro();
void RunApp();
bool RequestRestart();
std::string GetAttempt();
int main() // entry point of the application
{
printIntro();
RunApp();
RequestRestart();
return 0;
}
void printIntro() {
// introduce the program
constexpr int WORD_LENGTH = 8; // constant expression
std::cout << "Welcome to the Bull and Cow guessing game\n";
std::cout << "Can you guess the " << WORD_LENGTH;
std::cout << " letter isogram I am thinking of?\n\n";
return;
}
void RunApp()
{
// loop for number of attempts
constexpr int ATTEMPTS = 5;
for (int count = 1; count <= ATTEMPTS; count++)
{
std::string Attempt = GetAttempt();
std::cout << "You have entered " << GetAttempt << "\n";
std::cout << std::endl;
}
}
std::string GetAttempt()
{
// receive input by player
std::cout << "Enter your guess: \n";
std::string InputAttempt = "";
std::getline(std::cin, InputAttempt);
return InputAttempt;
}
bool RequestRestart()
{
std::cout << "Would you like to play again?\n";
std::string Response = "";
std::getline(std::cin, Response);
std::cout << "Is it y?: \n" << (Response[0] == 'y'); //response must be in brackets
return false;
}
You have to change this line
std::cout << "You have entered " << GetAttempt << "\n";
instd::cout << "You have entered " << Attempt << "\n";
In this way you do not print the address of the function, just like you did before, but the variable in which you stored the return value of the GetAttempt function.
You are printing a pointer to GetAttempt. Instead print Attempt:-
std::cout << "You have entered " << Attempt << "\n";

How to use cin inside a function?

I am new to c++ and am trying to make a simple text based game. The code below is supposed
to welcome the user to the game and ask whether or not the user wants to start the game. I don't get any build errors, but when I run it all it shows is a blank screen. What exactly am I doing wrong?
Code below:
string D1(string Original)
{
cin >> Original;
return Original;
}
int main ()
{
string Decision1;
cout << "Welcome to [game name]" << endl;
cout << "Would you like to start the game?" << endl;
cout << "Yes/No" << endl;
string D1(Decision1);
system("cls");
if (Decision1 == "Yes")
{
cout << "this happens" << endl;
}
else if (Decision1 == "No")
{
cout << "that happens" << endl;
}
}
You have to call D1, not create a new variable named D1:
std::string D1()
{
std::string Original;
std::cin >> Original;
return Original;
}
int main ()
{
std::cout << "Welcome to [game name]" << std::endl;
std::cout << "Would you like to start the game?" << std::endl;
std::cout << "Yes/No" << std::endl;
auto Decision1 = D1();
system("cls");
if (Decision1 == "Yes")
{
std::cout << "this happens" << std::endl;
}
else if (Decision1 == "No")
{
std::cout << "that happens" << std::endl;
}
}
string D1(string Original) should be string D1(string& Original) (ie: passing with reference)
and
string D1(Decision1); in main should be
D1(Decision1); because
string D1(Decision1); actually declares a new string variable, called D1 (same name as the function) and initializes it with the value of Decision1
This statement
string D1(Decision1);
is a definitiom of an object of type std::string with name D1 that initialized by object Decision1. As the object Decision1 is empty then and object D1 is empty.
What you meant is the following
void D1( string &Original )
{
cin >> Original;
}
//...
D1( Decision1 );
or the following
string D1()
{
string Original;
cin >> Original;
return Original;
}
//...
Decision1 = D1();
Take into account that if you use two if statements
if (Decision1 == "Yes")
{
cout << "this happens" << endl;
}
else if (Decision1 == "No")
{
cout << "that happens" << endl;
}
then you have to add a third statement with else because the user can enter neither "Yes" nor "No". Also you should compare strings independently of their case (upper case or lower case). So you have to convert strings to some common case.
For example
#include <cctype>
//...
for ( char &c : Decision1 ) c = std::toupper( c );
if ( Decision1 == "YES" )
{
cout << "this happens" << endl;
}
else if ( Decision1 == "NO" )
{
cout << "that happens" << endl;
}
else
{
//...
}
P.S. And here in comments there was suggested book "Programming -- Principles and Practice Using C++. " I do not advice this book for beginners. In fact it is a bad book for beginners. You will spend much time reading the book but your knowledge of C++ will be close to zero.
string D1(string Original)
Right now, the program will make a copy of the string you pass and place it into Original, so when you come out of the function, nothing will have happened to Decision1.
What you want it to do is pass the variable by reference.
Passing a variable by reference means the function isn't receiving a copy of what was passed, but the actual variable you passed (imagine a voodoo doll). Anything you do to the variable in the function will take effect on the variable passed.
Change the function header to:
string D1(string &Original)

having issues comparing strings

For some reason it skips over the first input an goes straight to the second one.
#include<iostream>
#include<string>
using namespace std;
int stringWork()
{
const int LENGTH = 40;
char firstString[LENGTH], secondString[LENGTH];
cout << "Enter First String: ";
//it skips over this following line
cin.getline(firstString, LENGTH);
cout << "Enter Another String: ";
cin.getline(secondString, LENGTH);
if (strcmp(firstString, secondString) == 0)
cout << "You entered Same string two times\n";
else
cout << "The two strings you entered are not the same\n";
system("pause");
return 0;
}
int main()
{
stringWork();
return 0;
}
it only allows input for one string
This piece of code works on my machine just fine. However, please do change #include <string> to #include <string.h> or #include <cstring>, and add #include <stdlib.h> or #include <cstdlib>.
Fix the code like this:
#include <iostream>
#include <string>
void stringWork()
{
const int LENGTH = 40;
char firstString[LENGTH], secondString[LENGTH];
std::cout << "Enter First String: " << std::flush;
std::cin.getline(firstString, LENGTH);
std::cout << "Enter Another String: " << std::flush;
std::cin.getline(secondString, LENGTH);
if (strcmp(firstString, secondString) == 0) {
std::cout << "You entered Same string two times." << std::endl;
} else {
std::cout << "The two strings you entered are not the same." << std::endl;
}
}
int main()
{
stringWork();
return 0;
}
Some notes about my version of your code:
Please don't use using namespace std.
Use std::flush to flush the characters in the output stream. This is necessary because usually the characters are only flushed with std::endl or in some implementations if you add a newline character.
Avoid mixing C and C++ code as you did. Use the std::getline method to read a line directly into a std::string. Shown in the next example.
Please care about your code style, especially if you post it in the public.
A even better implementation would avoid any C code and use just C++:
#include <iostream>
#include <string>
void stringWork()
{
std::cout << "Enter First String: " << std::flush;
std::string firstString;
std::getline(std::cin, firstString);
std::cout << "Enter Another String: " << std::flush;
std::string secondString;
std::getline(std::cin, secondString);
if (firstString == secondString) {
std::cout << "You entered Same string two times." << std::endl;
} else {
std::cout << "The two strings you entered are not the same." << std::endl;
}
}

learning c++, outputting variable in structure

Say I have a structure as follows
struct stock{
string ticker;
double price;
double volume;
double eps;
};
If I want to output one of the variables such as price when asked for it would I have to do a large if/else or switch statement to match up the user input with the member or is there a more elegant way to do it because I know stock.userInput does not work.
there's no special keyword to find your variable(sorry to burst your bubble), You would have to use a logical statement. It would go along:
cout << "What would you like to see? (1)Price (2)etc...etc...";
cin >> input;
switch(input)
{
case 1:
cout << Obj.Price;
break;
case 2:
cout << //....
break;
}
I personally like using keys and a switch statement, it tends to be a lot cleaner and easier to go back and modify later in the program.
struct stock s1;
cout<<" price is:"<< s1.price;
If you want to get rid of the large switch/if statement, you can use map with string and a pointer-to-member. Assuming your stock struct, you can use:
Define the map (for doubles here) and initialize it:
std::map<std::string,double stock::*> double_members;
double_members["price"]=&stock::price;
double_members["volume"]=&stock::volume;
double_members["eps"]=&stock::eps;
And use it to look up some values:
stock stock1;
std::string input;
std::cin >> input;
if (double_members.find(input)!=double_members.end())
std::cerr << "Value for " << input << " is: " << stock1.*double_members[input] << std::endl;
else
std::cerr << "There's no field called " << input << std::endl;
It's limited to a single type, but you can't have a statement like std::cerr << A; and have A's type resolved during runtime. If you care only about string (or any other, but always the same) representation of the values, then you can wrap maps for different types in a class that searches all of them and outputs the value converted to a string (or something).
But it's probably easier to have the if statement, unless the struct is really big.
If it's okay with you that it doesn't work with g++ 4.7.1 and earlier (but does work with Visual C++ 11.0 and later), then like …
#include <sstream> // std::ostringstream
#include <string> // std::string
using namespace std;
struct Stock
{
string ticker;
double price;
double volume;
double eps;
string toString() const
{
ostringstream stream;
stream
<< "Stock("
<< "ticker='" << ticker << "', "
<< "price=" << price << ", "
<< "volume=" << volume << ", "
<< "eps=" << eps
<< ")";
return stream.str();
}
Stock(): ticker(), price(), volume(), eps() {}
};
#include <iostream>
#include <regex>
#include <stdexcept>
#include <stdlib.h>
bool err( string const& s )
{
cerr << "!" << s << endl;
exit( EXIT_FAILURE );
}
string lineFromUser( string const& prompt )
{
string line;
cout << prompt;
getline( cin, line )
|| err( "oh my, failed to read line of input" );
return line;
}
void cppMain()
{
Stock stock;
stock.price = 1.23;
string const s = stock.toString();
cout << s << endl;
string const fieldname = lineFromUser( "Which field u want? " );
regex const valuespec( fieldname + "\\s*\\=\\s*([^,\\)]*)" ); //
smatch what;
if( regex_search( s, what, valuespec ) )
{
cout << "As we all know already, " << what.str() << "." << endl;
}
else
{
cout
<< "!Sorry, there's no field named '"
<< fieldname << "'"
<< endl;
}
}
int main()
{
try
{
cppMain();
return EXIT_SUCCESS;
}
catch( exception const& x )
{
cerr << "!" << x.what() << endl;
}
return EXIT_FAILURE;
}
Example usage:
[d:\dev\test]
> foo
Stock(ticker='', price=1.23, volume=0, eps=0)
Which field u want? eps
As we all know already, eps=0.
[d:\dev\test]
> _

C++ char or logical operator? Why takes else{...} if correct?

#include <iostream>
int main()
{
char username[15];
char password[15];
std::cout << "Hello, please login to continue your action.<Max 15 Char>" << std::endl;
std::cout << "Username: ";
std::cin >> username;
std::cout << "Password: ";
std::cin >> password;
if (username == "User" && password == "qwerty")
{
std::cout << "Hello, creator.";
}
else
{
std::cout << "Invalid Login";
}
/*23 row*/ std::cout << std::endl << std::endl << "Username=" <<username << std::endl << "Password=" << password;
std::cout << std::endl << std::endl << "Press Enter to close the window . . . ";
std::cin.clear();
std::cin.sync();
std::cin.get();
}
When i type correct it should say Hello Creator but it only goes to invalid i thinked maybe char stores only 1 char thats why at 23 row i taked look what is stored in char username and pasword but everything is fine. Why then it takes Else {...} sentence?
There are two types of strings in C++. The kind you are using for username and password are old-style C strings. They are basically a sequence of characters in memory, terminated by a special character '\0'. Since they come from old C, you can not use things like comparison or assignment operators on them.
To compare two old-style C string you have to use the strcmp function:
if (strcmp(username, "user") == 0)
{
// username == "user"
}
A better solution is to use the new C++ string class: std::string instead, as it has lot more functionality built in. For example handling comparison.
Strcmp is ok when you code in c. It's greatly recommended that you use string in C++.
#include <iostream>
int main()
{
std::string username;
std::string password;
std::cout << "Hello, please login to continue your action.<Max 15 Char>" << std::endl;
std::cout << "Username: ";
std::cin >> username;
std::cout << "Password: ";
std::cin >> password;
if (username == "User" && password == "qwerty")
{
std::cout << "Hello, creator.";
}
else
{
std::cout << "Invalid Login";
}
std::cout << std::endl << std::endl << "Username=" <<username << std::endl << "Password=" << password;
std::cout << std::endl << std::endl << "Press Enter to close the window . . . ";
std::cin.clear();
std::cin.sync();
std::cin.get();
}
You're attempting to compare char[] with a char*. This is doing a pointer comparison instead of a string comparison and hence you're getting a false because they are a different pointer address. Use std::string for username and password and then you'll get a comparison you're expecting
std::string username;
std::string password;
I believe the issue is in the comparison. To compare character arrays, you need to use a function like strcmp to compare the contents of character arrays. If I recall correctly, I believe you are comparing pointers, not the contents of the character array, one of which is the item in quotes (such as "User" or "Qwerty").
I would suggest using std:string which is designed to use the == (as an operator) for the comparing the items and I think you will find it works much better and is easier to use for strings information.