I've created a guessing game where you have to guess randomly generated number in range from 1 to 100. I also managed to restrict a user if they enter a number that is out of the range, and requires new input. The problem is when you accidentally enter letters or symbols. Then it enters an infinite loop. I tried:
while(x<1 || x>100 || cin.fail())//1. tried to test if input failed (AFAIU it checks if input is expected type and if it is not it fails)
while(x<1 || x>100 || x>='a' && x<='z' || x>='A' && <='Z') // 2. tried to test for letters at least
while(x<1 || x>100 x!=(int)x)//3. to test if it is not integer
{ cout<<"Out of range";
cin>>x;
}
For one solution, you could try and use isdigit. This checks to see if input is actually a number. So you can do something like:
if(!(isdigit(x))){
cout << "That is not an acceptable entry. \n";
continue;
}
EDIT: I should say, that after researching this, I realized that for isdigit to work, the entry needs to be a char. However, this can still work if you convert the char into an int after it discovers that it's an int. Example:
if(!(isdigit(x))){
cout << "That is not an acceptable entry. \n";
continue;
}
else{
int y = x - '0';
}
That int y = x - '0' might seem odd; but it's there because you have to convert the char to an int, and according to the ASCII coding, to do so, you subtract the character '0' from the desired number. You can see that here: Convert char to int in C and C++
Related
I am writing a program to find a 4-digit address. The program should continually allow the user to enter digits until the correct answer is solved. Additional parameters are:
All four digits are different
The digit in the thousands place is three times the digit in the tens
place
The number is odd
The sum of the digits is 27
With the program I've written so far it gives me the same output of "address is correct" no matter the input is. Trying to figure out what I am doing wrong, but no success. This is the code I've written so far.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
int const Address = 9837;
int input;
char Y;
char N;
int sum;
int even;
int i;
cout << "Please enter a 4-digit number." << endl;
cin >> input;
{
while (input = Y || N)
{
if (input = Y)
cout << "Please enter a 4-digit number" << endl;
else if (input = N)
cout << "Good Bye!!" << endl;
return 0;
}
while (input != Address && Y && N)
{
if (sum = input == !27);
cout << "Not a valid address - the sum of the digits is not 27" << endl;
if (input % 2 == 0)
cout << "Not a valid address - the number is even." << endl;
}
input = Address;
cout << "Address is correct." << endl;
}
}
You include <cmath> and <string> but you don't use anything from that headers.
Declare/define variables as close to where they're used/needed.
You are using the variables N and Y uninitialized. They contain an indeterminate value (=garbage). If char happens to be unsigned, reading an indeterminate value (an uninitialized (unsigned) char) under a few certain conditions is allowed. But you use N and Y in a way where reading their values causes undefined behaviour.
The variables even and i are never used.
With cin >> input; you try to extract an integer from standard input. If the user would enter Y or N or anything else that is not an integer, extraction would fail. You need two different ways to get the users input: 1 to let the user enter his guessed number and 1 to let the user choose if he wants to play again.
You introduce a block ({) after cin >> input; that serves no purpose.
while (input = Y || N) ... Comparison is done with the operator == in C++ (and C) but = is assignment. The expression input = Y || N assigns the result of Y || N to input but since Y and N are uninitialized and chances that both contain the value 0 is quite low (0 || 0 would evaluate to false), input will almost always be 1 (true converted to an int is 1) and the loop will always execute.
Actually, reading the values of Y and N causes undefined behaviour because they're uninitialized. Theoretically (since the compiler knows that Y and N have indeterminate value), it can generate any code it likes.
Within the first while-loop:
if (input = Y) // is again an assignment, not a test for equality
cout << "Please enter a 4-digit number" << endl;
else if (input = N) // again
cout << "Good Bye!!" << endl;
return 0; // will always exit the program, no matter the value of input
In case all hell breaks loose and N and Y are both 0 by chance and thus the 2nd while-loop is reached, it is sure, that input is 0 (because otherwise the controlled statement of the 1st while-loop would have been executed and exited the program by return 0;). When input equals 0 it isn't equal to Address so input != Address yields true but since we know that N and Y are 0 (false) and true && false gives false, the controlled statement of the 2nd while-loop doesn't get executed.
I'll skip the contents of the controlled statement of the 2nd while-loop. Sufficive to say, they don't do what you think they do.
input = Address; // that assignment serves no purpose
cout << "Address is correct." << endl;
is the output you always get when the variables Y and N are 0, which might happen (especially when running debug-code).
Please, stay away from the source you're currently learning C++ from. Get a good textbook and start over.
Is the piece of code you have captured here missing something or incomplete? I see that Y, N and sum are not assigned any value and thus all conditions checks fail... Eventually it will display "Address is correct" always...
Remember that = and == are totally different.
= means an assignment. eg: int x = 100; means put the value of 100 into the variable x.
== means comparison or (is equal to). eg: if (x == 100), means if x has the value 100.
Also, If you're trying to make a choice variable for Yes or No,
You should do it this way:
char ans;
if (ans == 'Y' || ans == 'N")
Since your input variable is an int, and your choice variable is a char, your while statement is not valid.
A few things you need to know:
You should assign values to things before calling them
You should read about the difference between = and ==
If you want multiple inputs, your cin >> input; should be in your while loop
Your code is not well indented at some places
You are declaring a i integer, but you are never using it.
In other words: your compiler must be giving you a LOT of warnings. Did you look at them?
I am having trouble figuring out how to separate each digit in an integer number. Basically, I have to ask the user what the base number is, and then ask them for two integer numbers. Now, I have the task of checking to make sure each digit in the two integers is smaller than the base number (I have no idea how to do this!).
An example would be something like this:
Enter a base:
3
Enter your first number:
00120
Enter your second number:
11230
I would have to check each digit in the first and second number. Where the first number would be valid because all digits are smaller than 3, and the second number would be invalid because it has a 3 in it which is not smaller than the base.
I've spent multiple hours trying to figure this out on my own and have had no luck.
If you're asking for user input, you don't yet have any integers. You have text, and all you need to do is check whether the text contains valid digit characters. As long as you don't get into bases greater than 10, that's simple, because the characters '0' ..'9' are required to be contiguous and increasing, so you can convert a digit character to its numerical value by subtracting '0' from it.
bool is_valid(char ch, int base) {
return isdigit(ch) && ch - '0' < base;
}
If you are sure that the input does not contain any non-number characters, you can use the % operator to check every digit explicitly. Here is a simple representation of what I mean:
#include <iostream>
bool isValid(int numb, int base) {
do {
if (numb % 10 >= base) { // if the digit cannot be used with this base
return false; // the integer is invalid
}
} while (numb /= 10);
return true; // if all the digits passed the above test,
// the integer is valid
}
int main() {
int numb, base;
std::cin >> numb >> base;
std::cout << "input "
<< (isValid(numb, base) ? "is " : "is not ")
<< "valid " << std::endl;
return 0;
}
I'm supposed to make a program that counts the number of people in each age group:
0-16 (including 16) is infant
16-29 is young
29-55 is middle
55-75 is old
75+ is really old
The intervals are closed to the left and open to the right.
I wrote a program that compiles, but does not give me the correct values. I'm new at coding so can anyone point me in the right direction? Here is what I have:
#include <iostream>
using namespace std;
main()
{
int countinfant, countyoung, countmiddle, countold, countreallyold;
char age;
countinfant=0;
countyoung=0;
countmiddle=0;
countold=0;
countreallyold=0;
cout<< "Please Enter Ages. To end, enter *\n";
cin.get(age);
while (age>0 && age != '*')
{
if (age>=0 && age<=16) countinfant = countinfant + 1;
if (age>16 && age<=29) countyoung = countyoung + 1;
if (age>29 && age<=55) countmiddle = countmiddle + 1;
if (age>55 && age<=75) countold = countold + 1;
if (age>75 && age>=76) countreallyold = countreallyold + 1;
cin.get(age);
}
cout<< "\n The Number of Infant's Are: " << countinfant;
cout<< "\n The Number of Young's Are: " << countyoung;
cout<< "\n The Number of Middle's Are: " <<countmiddle;
cout<< "\n The Number of old's Are: " <<countold;
cout<< "\n The Number of Really Old's Are: " <<countreallyold;
cout<<endl;
return 0;
}
Actually your problem is very easy to figure out once I looked closer at the code.
The get function of input streams read a single character and not numbers. So if you enter the character 5 as input it will be read and stored in age as a character, and if the encoding used on your system is ASCII encoding (which is the most common these days) then the value for the character '5' is the integer 53.
You then proceed to use the character you have read as an integer, which as it is encoded will give you the wrong results.
To get the correct values you need to read an integer, however since you want to check for the asterisk to end the input you can't use normal integer input with the >> operator, which is why you used get I guess. The solution is to use strings and check the string for the asterisk, and if not an asterisk convert the string to an integer.
Something like
std::string input;
while (std::cin >> input && input != "*")
{
int age = std::stoi(input);
...
}
It does not work because you declared age as a char. The program reads the input as a char, so if you enter 0, the value in age will be the ASCII code of the character 0, which is 48 (0x30). You need to declare it as int age; and for the exit condition simply enter a negative value, e.g. -1, don't use the '*'.
Variable hey should be overwritten when I go through the for-loop, so if I don't enter 1, it says "bye", but then if I enter 1 when it goes through the loop, it should say "hello", but instead it's saying "bye".
#include <iostream>
using namespace std;
int main(){
char hey;
for (int n = 0; n <= 10; n++){
cout << "enter 1" << endl;
cin >> hey;
if (hey == 1)
cout << "hello\n";
else
cout << "bye";
}
}
The character '1' with ASCII numer 49 is different from the number 1.
Use
if (hey == '1')
If you want to compare something to the character a, you´ll have to use 'a' too. It´s the same here.
The problem is hey is of type char. Therefore the input read from the console is interpreted as a char. You can either make the comparison if (hey == '1') or change the type of hey to something such as int.
If the user enters '1', char will be the character code for '1', which is 49.
https://msdn.microsoft.com/en-us/library/60ecse8t(v=vs.80).aspx
You could change your code to either
if (hey == '1')
or
if (hey == 49)
The title for this post is incorrect, by the way.
Change char hey to int hey. It will work as you expect.
You are comparing Ascii character value to Integer . Ascii value of 1 is 49
I am currently learning C++ and I have been asked to make a program which will calculate the interest that would be paid on a deposit of a given size. One of the requirements is that we display an error message when non-integer data is entered.
I however cannot work out how to detect if non-integer data has been entered. If anyone could provide an example of how this problem is solved it would be much appreciated!
You don't have to check yourself. The expression (std::cin >> YourInteger) evaluates to a bool, whcih is true if and only if YourInteger was succesfully read. This leads to the idiom
int YourInteger;
if (std::cin >> YourInteger) {
std::cout << YourInteger << std::endl;
} else {
std::cout << "Not an integer\n";
}
this should be a clear enough starting point.
char* GetInt(char* str, int& n)
{
n = 0;
// skip over all non-digit characters
while(*str && !isdigit(*str) )
++str;
// convert all digits to an integer
while( *str && isdigit(*str) )
{
n = (n * 10) + *str - '0';
++str;
}
return str;
}
You need to find out if the input value contains non numeric characters. That is, anything other than 0-9.
You have to first take input as string and then verify if every digit is indeed numeric.
You can iterate the string and test if each character is a valid digit using the built in function isdigit() defined in <cctype>. You might also want to allow for a single comma if you're working with decimal numbers.