I'm trying to use std::cin whilst having one option loop back to the start. The loop works perfectly but when I add in an extra option to one of the if statements then type that in, it doesn't think that what I chose is an option.
#include <iostream>
#include <string>
#include <windows.h>
#include <chrono>
#include <thread>
using namespace std;
int main() {
string choice;
char restart;
do {
choice.clear();
cout << "Which do you take? " << endl;
cin >> choice;
if (choice == "all") {
//cout code
restart = 'y';
}
else if (choice == "dagger" || choice == "the dagger") {
choice.clear();
cout << "You pick up the dagger" << endl << endl;
return 0;
}
else {
choice.clear();
cout << "That isn't an option, pick again... "<< endl << endl;
sleep_for(1s);
restart = 'y';
}
} while (restart == 'y');
}
When I type in "dagger", it works just fine, but when I type in " the dagger" it says runs the else code, then loops back to "Which do you take" and then chooses "dagger" instantly.
You're using std::cin with the >> operator. This operator reads formatted input (words) instead of unformatted input (lines). Rather than reading "the dagger", your program is simply reading "the", and leaving "dagger" in the input buffer for later.
To read unformatted input to choice, use std::getline(std::cin, choice); instead.
Related
I am pretty new to c++ and im having an issue trying to get my program out of a loop when a string is entered for the variables cont, and answer. In python it is pretty easy to do simple checks but I am not sure what I should be doing in cpp. I tried doing a check using if(typeid(answer)) == typeid(string)) but this doesnt work. I havent tried putting a check for
'y'||'Y'||'n'||'N' for cont but im assuming it would be something like that? just check for those 4 characters?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int main() {
unsigned seed;
char cont = 'y';
int answer = 0;
seed = time(nullptr);
srand(seed);
rand() % 100 + 1;
cout << "Lets play a math game!\n";
while(cont == 'y')
{
int num1 = rand() % 100 + 1;
int num2 = rand() % 100 + 1;
cout << "What is the result of this addition? \n " << num1 << '\n' << "+" << num2 << endl;
cin >> answer;
if (typeid(answer)==typeid(string))
{
while(typeid(answer) == typeid(string))
{
cout << "Please enter an integer!" << endl;
cin >> answer;
}
}
else if (typeid(answer) == typeid(int)) {
if (answer == (num1 + num2)) {
cout << "You are correct, would you like to play again?" << endl;
cin >> cont;
} else {
cout << "You were incorrect, would you like to try again? enter y/n" << endl;
cin >> cont;
}
} else {
answer = 0;
cout << "You did not enter an integer!\n" << endl;
cout << "Would you like to try again?" << endl;
}
}
return 0;
}
How can i check a variable type in a conditional statement in c++?
You do that already, though I'd do this instead:
#include <type_traits>
#include <iostream>
int main() {
int answer =0;
if constexpr(std::is_same_v<int,decltype(answer)>) {
std::cout << "answer is indeed an int";
}
}
However, this will always print the expected answer is indeed an int, because answer is an int not something else. If the user enters invalid input the variable answer declared as int will not turn into a std::string.
would something like if(inRange(0,200,answer)) work?
No it would not. std::cin >> answer; either succeds to read a number, or it fails and then 0 is assigned to answer. You cannot decide if valid input was entered by looking at answer only.
To check if the user entered valid input you can check the state of the stream:
#include <iostream>
#include <limits>
int main() {
int answer =0;
while(!(std::cin >> answer)){
std::cout << "please enter a number\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << answer;
}
Note that this accepts for example 42asdf as valid input, because std::cin >> answer does read 42 before it encounters something that is not a number. For something more sophisticated you can read a std::string and parse that.
I've created a program that asks for shoe size. If the shoe size is correct, the user will get a message that says, "You are correct would you like to try again?" They can either answer yes or no. If they select "no" the program will break and they will get another message that says, "Thanks for playing!"
Is there a way to basically force the program to break back into the while loop if the user enters yes as an answer instead of no?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int shoesize = 13;
int input;
string answer;
while (input != shoesize) {
cout << "Guess my shoe size!";
cin >> input;
if (input == shoesize) {
cout << "You are correct! Thanks for Playing! Would you like to play again? \n";
cin >> answer;
if (answer == "no") {
cout << "Thank you for playing!";
}
}
}
return 0;
}
Easily the best way to write something that "repeats continuously until you want to quit" is to just do something like this:
while(true) {
.. do something ..
.. ask "do you want to quit" ..
if (answer == "yes") {
break;
}
}
Programmers will instantly recognize the while(true){} "endless" loop, and look for the break statement which – as the name implies, "breaks out of" the innermost loop, ending the "endless" loop. One nice thing about this design is that you can use the break statement in more than one place within the loop as needed. (Within a function, you can also return.)
How about this.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int shoesize = 13;
string answer;
int input = 0;
while (input != shoesize && answer != "no") {
cout << "Guess my shoe size!";
cin >> input;
if (input == shoesize) {
cout << "You are correct! Thanks for Playing! Would you like to play again? \n";
cin >> answer;
if (answer == "no") {
cout << "Thank you for playing!";
return 0;
}
}
}
}
I'm trying to write a program, which shows a custom message in the console when I type load. But I can't seem to get it to work. :/
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
int main()
{
int commands();
string text;
cout << "Write your registered e-mail to continue...\n";
cin >> text;
string input;
cout << "\n";
cout << "Welcome " << text << endl;
cout << "\n";
cout << "www.steamcommunity.com/id/thetraderdazz> ";
cin >> input;
if (input = load);
cout << "loading...";
system("pause");
return 0;
}
It also gives me the following error:
identifier "load" is undefined.
if (input = load);
There are three mistakes with this line. The first is that you used the assignment operator = instead of comparison operator ==. The former assigns, the latter compares.
The second mistake is that you placed a semicolon after the parenthesis, indicating an empty body. Your compiler should have given you a warning about this.
Finally, there is no variable load. You mean to compare to string literal "load".
Fix to
if (input == "load")
cout << "loading...\n";
You probably intended the following
if (input == "load") {
cout << "loading...";
}
I'm trying to learn C++ by writing a simple console application. The user navigates the main menu by entering a number stored in a variable which a switch statement then uses to determine what to do. It's pretty simple. :)
The issue that's bugging me is that when the program reaches the cin statement, pressing return without entering a number doesn't "exit" the statement but just bumps it down to the next line. I guess this makes sense, but how can I make it so pressing return with no previous input just "exits" or "cancels" the cin statement?
Below is a shortened idea of what my application sort of looks like:
int main()
{
int mainMenuSelector;
while(mainMenuSelector != 4){
cout << "--- MAIN MENU -----------------" << endl;
cout << "[1] First Option" << endl;
cout << "[2] Second Option" << endl;
cout << "[3] Third Option" << endl;
cout << "[4] Exit Application" << endl;
cout << "-------------------------------" << endl;
cout << "Selection: ";
cin >> mainMenuSelector;
// This is the statement I want to move along from
// if the user presses the return key without entering any input.
switch(mainMenuSelector){
case 1:
doSomething();
break;
case 1:
doSomething();
break;
case 2:
doSomething();
break;
case 3:
doSomething();
break;
}
}
return 0;
}
std::string input;
while (std::getline(std::cin, input) && !input.empty()) { /* do stuff here */ }
You might want to go further and verify that the input is valid, doesn't just have a bunch of spaces, etc...
Pressing enter with no input results in an empty string value.
You can do this (try it and adapt it to your code):
#include <string>
#include <iostream>
using namespace std;
int main() {
string s;
getline(cin, s);
while(s != "") { // if the person hits enter, s == "" and leave the loop
cout << s << endl;
getline(cin, s);
}
return 0;
}
If you're specifically looking for options which use the stream operators (rather than parsing the input yourself), you might consider std::stringstream. For example:
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
void ExampleCaptureInput()
{
int value;
string s;
getline(cin, s);
if (s != "")
{
stringstream sstream(s);
sstream >> value;
}
}
I am a beginner in C++ and I was doing a do/while loop exercise and I am having trouble with it recognising the condition let alone it not looping properly. Can you guys give me a good foundation on how a simple problem like this is solved? I want to try and use a string to fulfill the condition of the do/while loop.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
double mean = 0;
string continuer;
do
{
cout << "Do you want to proceed?" << endl;
getline (cin, continuer);
cout << "something" << endl;
cin >> mean;
}
while (continuer == "Y" || continuer == "y");
return 0;
}
What I gather from your question and comment, you want to iterate through the loop at user's will.
You just want a char variable for that, like this.
string input ;
int number = 0 ;
do
{
cout << "Please enter a number" << endl ;
cin >> number ;
cout << "If you want to continue, Press Y" << endl ;
cin >> input ;
} while (input == "Y" || input == "y") ;
This do-while loop will execute at least one time, because the condition gets checked at the end of the loop execution. So even if the user does not press Y when asked the first time, this loop would have been executed once. After that, it will go on as long as the condition is fulfilled.
Learn more about the do-while loop here.
http://www.cplusplus.com/doc/tutorial/control/
What do you see? The body of the loop should be executed at least once. Does that happen?
Also, Continuer can be longer than one character, for instance "Y\n". Do test for that.
Here is what I would do:
#include <string>
#include <sstream>
using namespace std;
int main ()
{
double number = 0;
string continuer;
int loop = 0
do
{
cout << "Do you want to proceed?" << endl;
getline (cin, number);
cout << "something" << endl;
cin>> mean;
getline (cin, continuer);
cout << "Your answer was '" << continuer << "'." << endl;
loop = strcmp("Y", continuer);
if (loop != 0) strcmp("y", continuer);
if (loop == 0) cout << "Your choice is to stop." << endl;
else cout << "Your choice is to continue." << endl;
} while (loop == 0);
cout << "Bye" << endl;
return 0;
}
Be as explicit as you can untill you are confident enough in the language and the algorithm you are working with. It is easier to see what is happening and when it works it is easy to remove the 'cout' lines.