how to use strings in if statments (c++)? - c++

I'm beginning c++, and I want to do if statements with strings, but how.
#include <iostream>
using namespace std;
int main()
{
int a;
cout << "Do you like the food?"<< endl;
cin>> a;
if (a == "yes"){
cout<<"Thank you!"<<endl;
}
if (a == "no"){
cout << "That's mean!"<<endl;
}
return 0;
}
What do you think I should do? I like experimenting when learning a new programming language, but most of the time I can figure out how to do what I want to do, but my streak is up and I now need help. So, how do I do this properly? I think I should be able to do this as with some of the ideas I have involve more things like this, so please help me out here.
Thanks in advance!!!

The type of a should be std::string and not int.
So just change the declaration to:
std::string a;

Related

Changing variables during if-else if- else statements in C++

As I'm sure the question makes clear, I'm new and learning and I'm sure many will wonder why ask.....cause I get the rest of it, just not this. I am using C++ and am trying to make a self guessing program, that uses an algorithim given to me. I have played with this section of code multiple ways and so far the one thing I have narrowed down, is what its not doing, and I want to both understand why and how to fix it because nothing I have tried is working. The basic version of the code I have been playing with is this:
// test_room.cpp : This file contains the 'main' function. Program execution
//begins and ends there. This is where
//I am going to test some code to understand my mistakes and how to fix
//them.
//
#include "pch.h"
#include <iostream>
#include <cstdlib>
#include<ctime>
using namespace std;
int main()
{
char play = 'y';
while (play == 'y')
{
int bad = 27;
int a = 50;
int b = 1;
int good = ((a - b) / 2);
int s = 0;
cout << "\nBegin?";
cin >> play;
do
{
++s;
if (good > bad)
{
cout <<"\n" <<good;
cout <<"\n" << s;
--a;
}
else if (good < bad)
{
cout << "\n"<<good;
cout <<"\n" << s;
++b;
}
else
{
cout << "good job";
}
} while (s < 50);
}
cout << "\nOK\n";
return 0;
}
What my question is I have tried moving the variables, I have fixed brace issues, I have tried using cin>>good>>a or b(depending on >< ) and so far I can not manipulate variables a or b to get it to try to guess or figure out the number 27, all it does is repeat 24 50 times. What do I need to do to change the values of a and b based on the algorithim?
Good and bad are never changed in the loop, I don't really understand the purpose of you algorithm(it looks like a binary search, but not really), but if you aren't changing any values that the if conditions evaluate in the loop, then none of the other conditions will ever be evaluated.

Movement system with functions for text RPG

I am a beginner student of C++ and I am currently working on a text RPG. I've been able to implement various functions that help the user check location, interact with items, check inventory, look around, and so on, but I cannot seem to get a good working movement system.
Now, I understand that OOP is obviously going to be MUCH more efficient and less frustrating than going the function route, but I am doing this for a class, and we haven't learned anything about classes/objects yet (We haven't even gone over vectors/arrays in our class).
Here is my code to try and get the movement working:
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
using namespace std;
void movement(string action, int& currentRoom) {
if (action == "MOVE NORTH") {
if (currentRoom == 1) {
currentRoom = 2;
// This part is just to check if the loop happened and changed values.
cout << currentRoom << " " << "You are now in room two." << endl;
}
}
}
int main() {
int currentRoom;
string action;
cout << "Type 'move [direction]'" << endl;
currentRoom = 1;
getline(cin, action);
boost::to_upper(action);
// This is to check (for testing purposes for me) to see if the string
// converted to uppercase properly.
cout << action << endl;
getline(cin, action);
movement(action, currentRoom);
}
Now, this is not final code that I'm implementing into my game. I've just created a small file to try and work out the logic/syntax of this movement function. When I run this code, I am able to type in 'move north' and it successfully translates into MOVE NORTH, but the function doesn't seem to be calling or doing anything. What am I doing wrong here? Is there any way I can make this easier for myself, without fully leaning into OOP?
Like I said, I haven't been able to learn classes/objects aside from a bit of reading I've done online, and I feel like I would be taking on too much right now to try and learn/implement them properly in such a short time... but maybe it would be for the better if I did? I am not sure.
Any help and input is greatly appreciated.
int main() {
int currentRoom;
string action;
cout << "Type 'move [direction]'\n";
currentRoom = 1;
getline(cin, action);
boost::to_upper(action);
cout << action << '\n'; // here you verify
getline(cin, action); // but then you read again from stdin
movement(action, currentRoom); // and pass it on without changing it toupper.
}

Nesting int main() inside int main()

I am trying to make the simplest of all games, but with a loop function.
I'm given the error "a function-definition is not allowed here before '{', as well as a whole list of [Error] expected '}' at end of input.
Am I not allowed to nest int main() within another? Is that my issue at all? How do I accomplish this code without the nesting?
My knowledge and experience extend no more than a few chapters in two books.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
char again = 'y';
while (again == 'y')
int main()
{
srand(static_cast<unsigned int>(time (0)));
int secret = rand() % 100 +1;
int tries = 0;
int guess;
cout << "\tGuess the random number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++ tries;
if (guess > secret)
{
cout << "Too High!\n\n:";
}
else if (guess < secret)
{
cout << "Too Low!\n\n";
}
else
{
cout << "\nThat's It! You go it in " << tries << " guesses!\n";
}
} while (guess != secret);
}
cout << "\n\tWould you like to play again? (y/n): ";
char again;
cin >> again;
}
Your issue is nesting a main function inside of the existing main function. (This is not allowed.) In general, (With the exception of some stuff you can do with structs/lambdas which approximate that kind of functionality) you shouldn't nest functions inside of each-other. If you merely remove the function declaration, then your code should work fine:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
char again = 'y';
while (again == 'y')
{
srand(static_cast<unsigned int>(time (0)));
int secret = rand() % 100 +1;
int tries = 0;
int guess;
cout << "\tGuess the random number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++ tries;
if (guess > secret)
{
cout << "Too High!\n\n:";
}
else if (guess < secret)
{
cout << "Too Low!\n\n";
}
else
{
cout << "\nThat's It! You go it in " << tries << " guesses!\n";
}
} while (guess != secret);
cout << "\n\tWould you like to play again? (y/n): ";
cin >> again;
}
}
As far as I know, you cannot nest int main() inside of int main() for a number of reasons. In general, you can't define one function inside of another (defining "locally"). However, even if you can, your desire to do so should be a massive red flag that your design is off.
NOTE: As Nathan Oliver pointed out in the comments, you can forward-declare a function "locally" (within another function), but the actual implementation must be outside. Even doing this, you should usually second-guess your design at this point.
You need to be asking yourself what you're trying to do.
Are you wanting to group code together under a function to call repeatedly? Then create a separate function (with a different name) outside of main().
Are you wanting to repeat code? If so, you need a loop or a recursive function structure.
Are you wanting to split up some behavior into several functions, but hide all but one function involved? If so, look into classes (not necessarily objects - you can also have static classes.)
Those are just three of many possibilities, and deciding exactly what you want to do and how you want to do it is your responsibility alone to decide, as a programmer.
Brief recap: as far as C++ (and C) are concerned, if you're trying to declare any function inside any other function, you are doing something seriously wrong in design.
On a more technical note, you should also understand precisely what int main() is. It is a special function that is the entry point for your program. No C or C++ program can run without an int main().
You have to have a single instance of this function in main.cpp in order for your program to work. If you have more than one int main(), the computer cannot likely will not be able to find the entry point.
Besides that, having more than one function called main() anywhere in your code is a great way to confuse yourself and others.
In short, you should only have one int main() per program, no exceptions.

How do I combine user input with with if statements?

I'm making a program. For the program to work, I need to know how to combine user input (cin) with if statements, for example, something like:
start:
(program)
cout << "What would you like to do?";
if cin = "end" goto end;
if cin = "redo" goto start;
end:
return 0;
I know this isn't valid code, but I hope you understand what I'm trying to do. I need to know how to do this in C++, if possible, and if not, how to do the same thing.
Also, in Batch, doing something like :start: "bookmarks" the program, so that you can do a "GOTO start" command to jump back to it. How do you do that in C++?
This question is a little bit vague, but I'm trying to help you as good as I can.
First of all, the code for reading in a string is:
std::string input;
std::cin >> input;
(Of course, this requires that you include #include <string> and #include <iostream>).
Secondly, there is support for goto and labels in C++. But in most cases, there are better, more robust and more maintainable solutions to express yourself with. You want to learn more about while and for loops.
I hope that this answer provides some hints for you, where to start. Any basic C++ book will cover these topics and you should probably get one, if you really want to learn C++ by yourself.
Here is a small example that covers your questions:
#include <string>
#include <iostream>
int main( int, char ** )
{
std::string input;
while( true )
{
std::cout << "What would you like to do?" << std::endl;
std::cin >> input;
if( input == "redo" )
{
continue;
}
else if( input == "end" )
{
break;
}
else
{
std::cout << "Invalid input: " << input << std::endl;
}
}
return 0;
}

Stdin in C or C++: Spotify: Reverse Binary Puzzle

This is my first post on stack overflow so I apologize in advance if I miss a rule.
I tried to search a few posts however couldn't find what I was looking for.
I am trying to submit the Reversed Binary problem on Spotify however it is giving a reply "WRONG ANSWER". I have coded the problem in both C and C++, and I am able to validate answers for a lot of inputs. It doesn't seem that the problem is with the logic of the program. The puzzle states that "Input is read from stdin".
I have tried to use:
C: printf, scanf functions
C++: cout and cin functions (and writing "using namespace std" at the top)
C++: directly using std::cout and std::cin functions.
However none seems to work.
int stack[32];
top=-1
long inputNum,outputNum=0;
cout<<"Enter a Number\n";
cin>>inputNum;
while(inputNum>1) {
if(inputNum%2 == 0) {
push(0);
inputNum=inputNum/2;
} else if(inputNum%2 == 1) {
push(1);
inputNum=inputNum/2;
}
}
push(1);
int i=0,x=0;
while(top>-1) {
x=pop();
if(x==0) {
i++;
continue;
} else if(x==1) {
outputNum=outputNum+powl(2,i);
i++;
}
}
cout<<outputNum;
Ok. You have to realise is that spotify thing seems to be an automated bot which compiles and runs your submitted code.
So first off you're polluting the answer by providing your "Enter A Number" prompt. A bot wouldn't separate that from the real answer.
Secondly, I can't see how it compiles. What's this push(), pop(), top and stack code? Are you trying to use std::stack class? If so, check how you're using it.
On the other hand, if you're not using std::stack, but some of your own custom macros (not shown), then my bet would be to check those.
To read from stdin in c++, and write to stdout:
#include <iostream>
int main() {
unsigned int value;
std::cin >> value;
std::cout << reverse_binary(value);
}
You just need to implement reverse_binary (c:
You can extract this to a function which works with any streams:
void main_io(std::istream& input, std::ostream& ouput) {
unsigned int value;
input >> value;
output << reverse_binary(value);
}
And call it using cin and cout:
int main() {
main_io(std::cin, std::cout);
}
Or you can test it using stringstreams:
#include <sstream>
#include <cassert>
int main() {
std::istringstream input("13");
std::ostringstream output;
main_io(input, output);
assert(output.str() == "11");
}
Your streaming (though buggy) works fine.
I ran you code with,
int reverse_binary(int value)
{
if (value == 13) return 11;
return 1;
}
It must be within your own reverse_binary function.
What's your actual problem?