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";
}
}
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 just got into c++ and I'm just experimenting. I want to make a simple program which takes users input and calls one of 2 functions, then the function will print a line and ask the user if they want to go again. The issue is c++, for some reason, does not allow me to call main by simple saying main();
Is there any way to call the main function from another function? I am looking for the simplest solution there is, but I can't find anything :/
Here's the code:
#include <iostream>
#include <string>
using namespace std;
int do_math() {
cout << "Math" << endl;
string user;
cout << "would you like to go again? (y or n): " << endl;
cin >> user;
if (user == "y") {
main();
}
else if (user == "n") {
cout << "Okay, bye!";
exit(0);
}
return 0;
}
int do_eng(){
cout << "Eng";
string user;
cout << "would you like to go again? (y or n): " << endl;
cin >> user;
if (user == "y") {
main();
}
else if (user == "n") {
cout << "Okay, bye!";
exit(0);
}
return 0;
}
int main() {
string user;
cout << "Would you like to do math or end?:";
cin >> user;
if (user == "math") {
do_math();
}
else if (user == "end") {
do_eng();
}
return 0;
}
The issue is c++, for some reason, does not allow me to call main by
simple saying main(); Is there any way to call the main function from
another function? I am looking for the simplest solution there is, but
I can't find anything :/
No, you don't want to call main from any of your code.
Not that you should want to do this ... but the simplest solution is to provide a callable function, and get into it in the simplest way from main.
Perhaps:
int myMain()
{
string user;
cout << "Would you like to do math or end?:";
cin >> user;
if (user == "math") {
do_math();
}
else if (user == "end") {
do_eng();
}
return 0;
}
int main(int, const char**)
{
return myMain();
}
Lesson 1 - try to add another level of indirection (i.e. myMain()) does not have the restrictions of main()
Lesson 2 - learn something about recursion ... it seems you probably want to avoid it, here. (i.e. if you always invoke myMain(), how does your program ever terminate?
Lesson 3 - On my system, if the program terminates, I can up-arrow and launch it trivially. Terminal shells do this stuff for you. Perhaps this would be a better approach ... to always terminate unless the user selects one of the action choices (math, burp, etc.)
Lesson 4 - research other programs and how their user interface works. Find a model you like.
Note - I suppose, for your code to call myMain() again, you will need to 'forward declare' the function.
No, the standard specifically disallows calling main() from program code. What you want is to have a loop in main :
int main()
{
bool bContinue;
do
{
/* do something */
std::cout << "Do you want to go again?";
cin >> bContinue;
} while(bContinue);
}
the code bellow is a c++ code that works just perfectly, the teacher asked us to rewrite it in order to have the input and output in only one instruction.
i really don´t know how to, and i have done research for hours.
i'll really appreciate a hint on how to do this.
#include <iostream>
using namespace std;
int main()
{
int c;
cin >> c;
std;
if(c == 0) {
cout << "user sent 0" << endl;
}
else {
cout << "user sent a number different from 0" << endl;
}
return 0;
}
thanks for reading.
If your teacher considers an if-else statement as one instruction, I can propose this one:
#include <iostream >
using namespace std;
int main() {
int c;
if ( (cin >> c) && c==0 )
cout << ”user sent 0” << endl ;
else cout << ”user sent a number different from 0” << endl ;
return 0;
}
If he sees it more strictly, then you can try :
int c;
cout << ( (cin >> c) && c==0 ? "user sent 0" : "user sent a number different from 0" ) << endl;
return 0;
Conceptually, I love the last one. But when I read it again, it reminds me B.Kernighan's famous quote : "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."
This is the smallest I can do:
std::cout << (std::cin.get() == '0' ? "user sent 0" : "user sent a number different from 0");
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
}
Does it matter if I use a string or char for a simple input function? (aka y/n)
This is what I'm using at the moment:
using namespace std;
string somestr;
getline(cin,somestr);
if(somestr.empty())
{ //do something }
else if (somestr == "y"){
//do something else
}
else{}
And if it makes more sense to user char what would be the equivalent char code to this?
Yes, it matters, because std::string cannot be compared with a char using ==. You can compare it with a string literal:
if (somestr == "y")
or you can test the initial element of the std::string:
if (somestr[0] == 'y')
In the latter case, you might want to check the length as well, otherwise you would accept such inputs as "yacht" and "yellow." Comparing with a string literal containing the expected text is probably a better choice for most use cases.
I think James McNellis gives good rationale for why you would use either case. Personally, if you're asking a "yes/no" question, I find the single character easier because it minimizes the number of different scenarios you have to deal with.
Here's some sample code that you could use to read an answer from the user via a single character:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
//keep looping until the user enters something valid
while(true)
{
char answer;
cout << "Does this sound good (y/n)? ";
cin >> answer;
if(answer == 'y' || answer == 'Y')
{
//user entered yes, do some stuff and leave the loop
cout << "You answered yes!" << endl;
break;
}
else if(answer == 'n' || answer == 'N')
{
//user entered no, do some stuff and leave the loop
cout << "You answered no!" << endl;
break;
}
else
{
cout << "You did not enter a valid answer. Please try again." << endl;
//if we got bad input (not 'y'/'Y' or 'n'/'N'), wipe cin and try again
cin.clear();
cin.ignore(numeric_limits<int>::max(),'\n');
}
}
}
If you're planning on reading more than a single character answer though, then I think you're probably fine with getline and doing your reasoning that way.
It is better to use char because you only need to store one character
using namespace std;
char chr;
getline(cin,chr);
if(chr == null)
{ //do something }
else if (chr == "y"){
//do something else
}
else{}