Alright so I am doing an assignment and am getting frustrated. The assignment wants me to ask the user for a number then say if the number is even or odd, but if the user types "done" the program will exit.
So my question is how do you check the input for character/int at the same time, then decide which it is.
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
bool isEven(int userAnswer);
using namespace std;
int userAnswer;
int main()
{
cout << "Which number would you like to check?" << endl;
cin >> userAnswer;
if (isEven(userAnswer) == false)
{
cout << userAnswer << " is a odd number." << endl;
}
else if (isEven(userAnswer) == true)
{
cout << userAnswer << " is a even number." << endl;
}
cin.get();
cin.get();
return 0;
}
bool isEven(int userAnswer)
{
if (userAnswer % 2 == 0)
{
return true;
}
else
{
return false;
}
}
Read into a string (which works in both cases), then parse the string yourself.
Read into a std::string and exit if done is in the string. Otherwise convert to int and carry on as you are. Hint: see std::stoi
Related
I am trying to write a program that checks if a phrase is a palindrome or not, and in case nothing is entered or just whitespace, it should print out "empty".
At first, the user should type in the number of phrases that they are going to enter (e.g. 3), and then the phrases that are to be checked.
It works just fine, but when my first input is empty, it prints out "empty" again and again without asking for another phrase.
#include <iostream>
#include <string>
#include <iomanip>
#include <math.h>
using namespace std;
int main() {
int N;
int isPalindromeCounter=0;
int counter = 0;
string inputString;
cin >> N;
cout << "\n";
while (counter<N){
counter++;
cin.ignore(100, '\n');
cin >> noskipws >> inputString;
if (inputString.length()==0){
cout <<"empty\n";
continue;
}
int left = 0;
int right = inputString.length()-1;
if (inputString.length()>20){
cout <<"error\n";
continue;
}
bool isPalindrome = true;
while (left<right){
if (inputString[left] != inputString[right]){
isPalindrome = false;
cout << "no\n";
break;
}
left++;
right--;
}
if (isPalindrome){
cout << "yes\n";
isPalindromeCounter++;
}
}
double percentage = double(isPalindromeCounter)/double(counter)*100;
if (trunc(percentage) != percentage){
cout << setprecision(5) << percentage;
}
else {cout << percentage << ".000" ;}
return 0;
}
What am I doing wrong ?
I expected that it should print "empty" once, and then ask for another input, but it prints "empty" for all the inputs.
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 have only taken one C++ class and am planning on filling my grandma's children's names with different stuff, what I have currently is just filler. However when I try to debug myself by changing string type to integer like it tells me to I then just get new error codes. Here is what I have currently, the program is quite simple:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
string name;
string main() {
bool done = false;
while (!done) {
cout << "Enter one of your children's names, or press 'q' to quit" << endl;
cin >> name;
if (name = "q") {
done = true;
break;
}
else if (name = "Jason") {
cout << "Jason is your eldest son" << endl;
}
else if (name = "Aaron") {
cout << "Aaron was your second child" << endl;
}
else if (name = "Mandy") {
cout << "Mandy is your only girl" << endl;
}
else if (name = "Adam") {
cout << "Adam came after Mandy" << endl;
}
else if (name = "Ben") {
cout << "Ben is your youngest" << endl;
}
else {
cout << "That name does not exist for your children: try Jason, Aaron, Mandy, Adam, or Ben instead" << endl;
}
}
}
On your if and else if statement you need to change == instead of = (assignment) in order to check if the values of two operands are equal or not.
Also, in your String main() I would recommend to change it for just: int main()
Just to reiterate what everyone else has mentioned
Adjust your if/else compare operator ---> if (name == "q")
Use int main()
int main()
{
bool done = false;
string name;
while (!done)
{
if (name == "q")
{
done = true;
break;
}
// Remainder of code goes here
} // Close while loop
} // Close main()
I have been trying to create a simple while loop to cin numbers into a vector, with some basic input validation. However, I am finding some weird things happening with my code. I am trying to have it so that the user can input numbers until they type in '0', which will then end the loop. This works fine.
However, I am also trying to make it so that if they enter a non-int (i.e. 3.4, a), or if they enter a negative number, it couts "BAD INPUT" and then quits the program. When I type in a negative number, it works fine. But when I type in a non-int, it does not cout anything, but still quits the program...
Likewise, I am also trying to have it so that if they type in '0' first, without having put in any numbers beforehand, it couts "NO NUMBERS" and quits the program. This one also quits the program, but again, does not cout anything.
My code is as follows:
#include <iostream>
#include <vector>
//I know it is considered bad practice for the below part.
using namespace std;
int main()
{
vector<int> numberStorage;
while (cin) {
int numInput = 0;
cin >> numInput;
if (numInput == 0) break;
if (!cin || numInput < 0) {
cout << "BAD INPUT" << '\n';
return false;
}
if (numInput == 0 && numberStorage.size() == 1) {
cout << "NO NUMBERS" << '\n';
return false;
}
numberStorage.push_back(numInput);
}
return 0;
}
Can anyone help me and clarify as to where my logic/code is going wrong here on these input validations? Thank you for any help.
Try this:
#include <iostream>
#include <vector>
//I know it is considered bad practice for the below part.
using namespace std;
vector<int> numberStorage;
int main() {
while (true) {
int numInput = 0;
cin >> numInput;
if (cin.fail() || numInput < 0) {
cout << "BAD INPUT" << '\n';
break;
}
if (numInput == 0) {
cout << "Received 0" << endl;
break;
}
if (numInput == 0 && numberStorage.size() == 1) {
cout << "NO NUMBERS" << '\n';
return false;
}
numberStorage.push_back(numInput);
}
return 0;
}
In the original code, you were not checking for cin.fail().
When you were trying to store a value that was not an int inside numInput,
the cin was silently failing and as you initialized numInput to 0, it was exiting the loop as if the client had entered the number zero on console.
You can check that yourself by adding a cout on the zero value condition of the original code.
cheers
When cin fails, it will assign value 0 to numInput and your logic
if (numInput == 0) break;
silently exiting the program.
It would be a good practice if you call cin.clear() in case cin.fail() occurs in order to clear the error flag on cin, so that future I/O operations will work correctly.
Just a recommendation!
You can check by using cin.fail() just after setting integer for checking not number.
#include <iostream>
#include <vector>
using namespace std;
vector<int> numberStorage;
int main() {
while (cin) {
int numInput = 0;
cout << "Please enter:";
cin >> numInput;
if(cin.fail()) {
cout << "NO NUMBER" << "\n";
}
if (numInput == 0) break;
if (!cin || numInput < 0) {
cout << "BAD INPUT" << '\n';
return false;
}
numberStorage.push_back(numInput);
}
}
here is the result : https://onlinegdb.com/SyIWdqU9m
I am trying to have a loop continue to prompt the user for an option. When I get a string of characters instead of an int, the program loops indefinitely. I have tried setting the variable result to NULL, clearing the input stream, and have enclosed in try{}catch blocks (not in this example). Can anyone explain to me why this is?
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int menu(string question, vector<string> options)
{
int result;
cout << question << endl;
for(int i = 0; i < options.size(); i++)
{
cout << '[' << i << ']' << options[i] << endl;
}
bool ans = false;
do
{
cin >> result;
cin.ignore(1000, 10);
if (result < options.size() )
{
ans = true;
}
else
{
cout << "You must enter a valid option." << endl;
result = NULL;
ans = false;
}
}
while(!ans);
return result;
}
int main()
{
string menuQuestion = "Welcome to my game. What would you like to do?";
vector<string> mainMenu;
mainMenu.push_back("Play Game");
mainMenu.push_back("Load Game");
mainMenu.push_back("About");
mainMenu.push_back("Exit");
int result = menu(menuQuestion, mainMenu);
cout << "You entered: " << result << endl;
return 0;
}
It looks like there is a random element here, since result is not initialized.
In any case, test cin directly
if ( cin && result < options.size() )
and reset it upon invalid input so it will again perform I/O operations
result = 0; // inappropriate to initialize an integer with NULL
cin.clear(); // reset cin to work again
cin.ignore(1000, '\n'); // use \n instead of ASCII code