Completely new to C++. Trying to understand classes and objects, so far I get the gist of it, as it's nothing too complicated for the very basics. However, this code I have wrote is not working as intended. It works somewhat, however it asks for user input twice.
#include <iostream>
#include <string>
using namespace std;
class FooFoo {
public :
string GetName() {
cin >> name;
return name;
}
private:
string name;
};
int main()
{
FooFoo object;
if (object.GetName() == "John" || object.GetName() == "Chris")
{
cout << "Yes";
}
else {
cout << "No";
}
}
If I input "John", it will return yes right away. However, when I input anything else, it will prompt me to enter something again, and then the if/else acts accordingly to whatever I inputted.
You call object.GetName() twice which causes the input to be asked for twice. Store the result of this function to a variable and use that in the if statement. The || statement is short-circuited if the first expression is true. This leads to the second call not being executed if the first is true.
That is because GetName() is asking for input every time,
So the first time it is asking for x, if x isnt john it goes to the next test, which then gets input and tests that against x = chris.
try changing it to this:
int main()
{
FooFoo object;
string test = object.GetName()
if (test == "John" || test == "Chris")
{
cout << "Yes";
}
else {
cout << "No";
}
}
Hope that helps
Your current if statement effectively evaluates to:
if (object.GetName() == "John")
cout << "Yes";
else if (object.GetName() == "Chris")
cout << "Yes";
else
cout << "No";
Try entering Chris followed by John and you should get No.
Just call getName() before the if statement, store the value in a local variable, then test that instead:
string name = object.GetName();
if (name == "John" || name == "Chris")
cout << "Yes";
else
cout << "No;
Related
So, I'm triying to learn c++ (coming from python), and I wanted to make a program just to see if i could do it with what i've learned, here's the code
#include <iostream>
using namespace std;
int response(string i) {
if (i == "yes" or i == "Yes") {
cout << "\nHello, sad, I'm dad\n";
return(0);
}
else if (i == "no" or i == "No") {
cout << "Good for you pal\n";
return(0);
}
else {
cout << "Answer properly you overgrown flatworm\n";
response(i);
};
};
int main() {
string i;
cout << "Are you sad?";
cin >> i;
response(i);
};
Pretty simple huh? No. For some reason, yes and no answers work fine, but when I try something different I get insulted infinitely and the program crashes from exceeding it's memory limit. How do I solve this?
(English is not my native language, so feel free to correct any ortography mistakes)
At no point do you request further input. For bad input 'i', the response routine prints out an insult, and then calls itself with exactly the same string.
The response routine prints out an insult, and then calls itself with exactly the same string.
The response routine prints out an insult, and then calls itself with exactly the same string.
…
You need to allow the user to enter a new string, and then (if you want to use recursion) make the recursive call to validate the new input.
But as mentioned in the comment, this is not really a problem that needs a recursive solution.
This can be solved by eliminating recursion ad it involves moving the input routine inside of a function that's more self-contained:
int getResponse(string i) {
for(;;) {
string i;
cout << "Are you sad?";
cin >> i;
if (i == "yes" or i == "Yes") {
cout << "\nHello, sad, I'm dad\n";
return(0);
}
else if (i == "no" or i == "No") {
cout << "Good for you pal\n";
return(0);
}
else {
cout << "Answer properly you overgrown flatworm\n";
}
}
}
You have 2 issues:
In the else case, you are not asking for new user input.
You need to return the result of calling response(i), otherwise the code invokes undefined behavior.
else {
cout << "Answer properly you overgrown flatworm\n";
cin >> i;
return response(i);
};
Alternatively, since you never use the return value from response, you can just remove all the return statements, and make it a void function.
If you insist on using recursion then move the input and the check in the same function response() - that function doesn't need to return int at all. In main you can just call response().
void response()
{
string i;
cout << "Are you sad?";
cin >> i;
if (i == "yes" or i == "Yes")
{
cout << "\nHello, sad, I'm dad\n";
}
else if (i == "no" or i == "No")
{
cout << "Good for you pal\n";
return;
}
else
{
cout << "Answer properly you overgrown flatworm\n";
response();
}
}
int main()
{
response();
}
I made a C++ user input that detects when no value is being input, but it terminates the program on startup without outputting anything. Why?
#include <iostream>
int main() {
bool entered = false;
while(entered = false) {
std::cout << "Please enter thy name: ";
std::string name;
std::getline(std::cin, name);
std::cout << "Hello, " + name;
int length = name.length();
if(length > 0) {
std::cout << "Hello, " + name;
entered = true;
} else {
std::cout << "Thou did not enter thy name";
}
}
}
I already made a similar program in Java with a similar format and that one works fine.
This loop condition:
while(entered = false)
is wrong. Instead of comparing false and entered, you are assigning false to entered.
Instead, you need to do:
while(entered == false)
If you turn on warnings, for example with -Wall, the compiler will tell you that you are likely making a mistake here.
I can see that your main function starts with int but I can't see return 0, remember that if your function is not void then it must return something.
So I am new to C++, and I am working through a pdf tutorial that is getting me started with basic stuff. I was writing a simple case program, and I experienced something weird.
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
enum string_feeling {
eGood,
eBad,
eOk,
};
string_feeling hashit(string const& feeling) {
if (feeling == "Good" || feeling == "good" || feeling == "GOOD") {
return eGood;
}
if (feeling == "Bad" || feeling == "bad" || feeling == "BAD") {
return eBad;
}
if (feeling == "Ok" || feeling == "ok" || feeling == "OK") {
return eOk;
}
else cout << "";
}
int main() {
string username;
cout << "Hello! Please enter your first name here: \n";
cin >> username;
cout << "Hello, " << username << "!\n";
cout << "How are you today? ";
string feeling;
cin >> feeling;
cout << endl;
switch (hashit(feeling)) {
case eGood:
cout << "That's great!";
break;
case eBad:
cout << "I hope you are happy soon!";
break;
case eOk:
cout << "That's good.";
break;
default:
cout << "Ok.";
}
}
Whenever I didn't have the "else" after the "if (feeling == ok)" stuff, the default case would never be called and if I entered something random it would give me the text from the eGood case. I was wondering why this is happening and since I'm learning C++ I didn't want to just brush it off not ever knowing why it worked after I put the else statement in there. So, if anyone could explain this to me that would be great! Sorry for my bad grammar.
Compile your program with warnings enabled like g++ -Wall -Wextra -Werror and it won't even compile, because string_feeling hashit(string const& feeling) does not return a value in all cases.
Compiling code without warnings enabled is a surefire way to waste time.
When none of conditions in the three if statements in hashit function become true, no return statement is executed in the function and undefined behavior is invoked.
(Quote from N3337 6.6.3 The return statement)
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
To avoid this, you should add one more kind to the enum
enum string_feeling {
eGood,
eBad,
eOk,
eOther // add this
};
and return it when no conditions are met.
string_feeling hashit(string const& feeling) {
if (feeling == "Good" || feeling == "good" || feeling == "GOOD") {
return eGood;
}
if (feeling == "Bad" || feeling == "bad" || feeling == "BAD") {
return eBad;
}
if (feeling == "Ok" || feeling == "ok" || feeling == "OK") {
return eOk;
}
else cout << "";
return eOther; // add this
}
You always have to return a value else the behavior is undefined
If you cannot modify your enum to add a case for an unknown feeling you can modify hashit to return true if feeling is valid and in that case to set the output parameter with the corresponding enum value, else to return false without setting the output parameter :
#include <iostream>
#include <string>
using namespace std;
enum string_feeling {
eGood,
eBad,
eOk,
};
bool hashit(string const& feeling, string_feeling & r) {
if (feeling == "Good" || feeling == "good" || feeling == "GOOD") {
r = eGood;
}
else if (feeling == "Bad" || feeling == "bad" || feeling == "BAD") {
r = eBad;
}
else if (feeling == "Ok" || feeling == "ok" || feeling == "OK") {
r = eOk;
}
else
return false;
return true;
}
int main() {
string username;
cout << "Hello! Please enter your first name here: \n";
cin >> username;
cout << "Hello, " << username << "!\n";
cout << "How are you today? ";
string feeling;
cin >> feeling;
cout << endl;
string_feeling f;
if (! hashit(feeling, f))
cout << "I do not understand how you are" << endl;
else {
switch (f) {
case eGood:
cout << "That's great!" << endl;
break;
case eBad:
cout << "I hope you are happy soon!" << endl;
break;
case eOk:
cout << "That's good." << endl;
break;
}
}
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -Wall c.cc
pi#raspberrypi:/tmp $ ./a.out
Hello! Please enter your first name here:
bruno
Hello, bruno!
How are you today? good
That's great!
pi#raspberrypi:/tmp $ ./a.out
Hello! Please enter your first name here:
bruno
Hello, bruno!
How are you today? aze
I do not understand how you are
pi#raspberrypi:/tmp $
Out of that :
to name your enum string_feeling is not very clear, whatever the feeling was input as a string, better to just name it Feeling
it can be practical in hashit to get the string by value to change it to lowercase then to just compare it with with "good" "bad" and "ok" or to use strcasecmp on its .c_str(), allowing to also manage "gOoD" etc
If no if conditions will meet, hashit went to
else cout << "";
Since you didn't explicitly write the return statement, the function returns the default value 0, which is equal to eGood.
However, the default return value is not always 0. This is an undefined behaviour.
If you runs this code with a different compiler, you may get different results.
Today I want to test if a user types the word "yes" in console application, then the function will proceed, however, I am unable to do so. (I am a new person, sorry)
Any help on this?
I know when testing a variable like.. int x = 14, and if (a < 14) print something.. but instead of number I'd like to try with text.
Here is the source code:
int main()
{
char a = yes;
char b = no;
cout << "hi, press yes to start or no to cancel";
cin >> a;
if (a == yes)
{
cout << "Cool person";
}
else if(b == no)
{
cout << "not a cool person";
}
}
I keep getting "yes" is not defined in scope.
Any help would be appreciated. Thank You!
At a bare minimum, the following problems exist in your code:
Tokens yes and no are identifiers. If you wanted them to be characters, that would be 'yes' and 'no. Except that they're not characters since they're too long. So, they should probably be strings like "yes" and "no".
The b variable is totally useless here, you should have one variable for receiving information from the user and checking it against multiple possible values. It's also a good idea to choose meaningful variable names.
You aren't including the requisite headers, nor are you using the correct namespace for the std functions and types (either by explicitly prepending std:: to each, or with a using namespace std for them all).
With that in mind, try out the following program as a starting point for your further education:
#include <iostream>
#include <string>
int main() {
std::string userInput;
std::cout << "Hi, enter yes to start or no to cancel: ";
std::cin >> userInput; // probably better: std::getline(std::cin, userInput);
if (userInput == "yes") {
std::cout << "Cool person\n";
} else if (userInput == "no") {
std::cout << "Not a cool person\n";
} else {
std::cout << "Hey, can't you read? I said yes or no :-)\n";
}
}
I'm making a small program that uses a if else statement, but instead of using numbers to control the flow i want to be able to make the control work with with yes and no;
for example:
cout << "would you like to continue?" << endl;
cout << "\nYES or NO" << endl;
int input =0;
cin >> input;
string Yes = "YES";
string No = "NO";
if (input == no)
{
cout << "testone" << endl;
}
if (input == yes)
{
cout << "test two" << endl;
//the rest of the program goes here i guess?
}
else
{
cout << "you entered the wrong thing, start again" << endl;
//maybe some type of loop structure to go back
}
but I can't seem to get any variations of this to work, i could make the user type a 0 or 1 instead but that seems really stupid, i'd rather it be as natural as possible, users don't speak numbers do they?
also i need to be able to simply add more words, for example "no NO No noo no n" all would have to mean no
hopefully that makes some sense
also i would love to make this using a window but i've only learned basic c++ so far not even that and i cant find any good resources online about basic windows programming.
You're not reading in a string, you're reading in an int.
Try this:
string input;
instead of
int input = 0;
Also, C++ is case-sensitive, so you can't define a variable called Yes and then try to use it as yes. They need to be in the same case.
btw, your second if statement should be an else if, otherwise if you type in "NO" then it will still go into that last else block.
First of all, input must be std::string, not int.
Also, you've written yes and no wrong:
v
if (input == No)
// ..
// v
else if (input == Yes)
^^^^
If you want your program to work with "no no no ..", you could use std::string::find:
if( std::string::npos != input.find( "no" ) )
// ..
The same with "Yes".
Also, you could do this to be almost case-insensitive - transform the input to upper-case letters (or lower, whatever ), and then use find.This way, yEs will be still a valid answer.
bool yesno(char const* prompt, bool default_yes=true) {
using namespace std;
if (prompt && cin.tie()) {
*cin.tie() << prompt << (default_yes ? " [Yn] " : " [yN] ");
}
string line;
if (!getline(cin, line)) {
throw std::runtime_error("yesno: unexpected input error");
}
else if (line.size() == 0) {
return default_yes;
}
else {
return line[0] == 'Y' || line[0] == 'y';
}
}
string input;
cin >> input;
if (input == "yes"){
}
else if (input == "no"{
}
else {
//blah
}