I am working at a vending machine software. I cannot get the if statement to work. It just simply ignores it.
// Program.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char number;
cout << "Hello. Please choose a drink type ! \n\n1.Coca-Cola \n2.Coca-Cola ZERO \n3.Pepsi\n" ;
cin >> number;
if (number == 1)
cout << "Please tip in 8$";
}
You're comparing a char variable to an int value. You need to change one or the other so they match. Either make number an int:
int number;
...
if (number == 1)
or compare it to the character '1':
char number;
...
if (number == '1')
The distinction here is between the number 1 and the character '1' which has an ASCII value of 49.
As number is a character, you want the comparison to use a character and not the integer value 1. i.e.
if (number == '1')
Related
I have this code right here that compiles just fine getting the first digit of a 10 digit number.
I am wondering how to get my code to get the first digit of a 16 digit number?
I have tried changing 10 to 16 in the while loop and my program does not count the first digit. Here is my code down below:
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter a number : " << endl;
cin >> number;
// cout << "Last digit is : " << number % 10 << endl;
while(number >= 10)
{
number = number/10;
}
cout<< "First digit is : "<< number << endl;
return 0;
}
int has at least 16 bits. The exact size is implementation defined. Even with 32 bits the maximum value is 2147483647. You cannot store a 16 digit number in an int.
You can store numbers with more digits than any integer type can hold in a std::string. Because just reading some string from the user and printing the first character would be too much cheating, at least you should check that the user actually did enter a number:
#include <iostream>
#include <limits>
#include <cctype>
int main() {
std::cout << "max int : " << std::numeric_limits<int>::max() << "\n";
std::string number;
std::cin >> number;
for (const auto& c : number) {
if (std::isdigit(c) == 0) {
std::cout << c << " is not a valid digit !";
return 1;
}
}
if (number.size() > 0 && number[0] != '0') std::cout << number[0];
else std::cout << "invalid input";
}
Live Demo
Learning how to use <string> will prove very, VERY useful for you:
#include <iostream>
#include <string> //extremely useful
using namespace std;
int main()
{
string aux;
string number;
cout<<"Enter a number: "<<endl;
cin>>aux;
number=aux.substr(0,1); //create a substring of aux, starting from the first position (first argument) and getting only one character (second argument)
cout<<"First digit is "<<number<<endl;
return 0;
}
if you need the variable as int, use stoi():
int num=stoi(number);
if you want to be sure the input has 10 or 16 digits, use size():
int size=aux.size();
if (size!=10) //or 16, whatever you want
cout<<"invalid number"<<endl;
Changing 10 with 16 won't work at all, the problem is the upper limits of an int which is usually 2147483647, inputing values above this will not work, meaning the digit will always be 2.
What you need to do is to use a larger type. You can safely use long long int which can take 19 digits.
long long number;
It's max value is guaranteed to be 9223372036854775807 at least.
Ideally, if possible, you should extract the user input as a string, it would be a much easier task to then extract the first character as exemplified by largest_prime_is_463035818.
This question already has answers here:
Single quotes vs. double quotes in C or C++
(15 answers)
Closed 4 years ago.
Have to do this for the first cs course I'm taking. It's a basic calculator that takes an operator and a value and calculates the total (total beginning at 0).
#include <iostream>
using namespace std;
int main()
{
char oprtr;
float value, total = 0.0;
cin >> oprtr >> value;
while (oprtr != "q")
{
if (oprtr == "+")
total += value;
else if (oprtr == "-")
total -= value;
}
}
It's not finished but already having issues with it. It gives errors saying something along the lines of "prohibits comparing char values to int values"
Double quotes ("q") are for strings. Single quotes ('q') are for characters.
So:
while (oprtr != 'q')
{
if (oprtr == '+')
total += value;
else if (oprtr == '-')
total -= value;
}
Char means Character and you must use single quotes '' for these, double quotes "" are for strings.
The reason you are getting this error is because you're attempting to compare a character to a string literal (a const char), the exact error you're getting will be:
Operand types are incompatible ("char" and "const char").
The below code will fix this error:
#include <iostream>
using namespace std;
int main()
{
char oprtr;
float value, total = 0.0;
cin >> oprtr >> value;
while (oprtr != 'q')
{
if (oprtr == '+')
total += value;
else if (oprtr == '-')
total -= value;
}
}
And also, since you are reading the statement or the expression once, there is no need for you to loop while the character is not equal to 'q'. You should basically perform one operation. Also, switch is a very useful construct for comparing literals instead of several if's. So I would simplify that as.
#include <iostream>
using namespace std;
int main(){
char op;
float value, total = 0.0;
cin >> op >> value;
//it is important at this stage to check for errors, as they are most likely
//to occur.
if(!cin){
cerr << "Error: format unknown! \n"; //basic error handled here, the prog outputs the error
}
//now perform the calculation
switch(op){
case '+': total += value;
break;
case '-' : total -= value;
break;
case 'q' : break; //i presume q is your quit character
default: /*unknown character*/ cerr << "Unknown operation! \n";
}
cout << "Total: "<<total << endl;
return 0;
}
this basically reads in one expression and add it to the total. You can modify it to read as long as you want.
Comparing string length is a common function in C programming, as it allows you to see which string contains more characters. This is very useful for sorting data. Comparing strings requires a special function; do not use != or ==.
http://www.techonthenet.com/c_language/standard_library_functions/string_h/strcmp.php
The loop in the function require() takes 3 conditions, a > b or "a" or "b" aren't digits. Even when I don't satisfy the conditions and put 2 integers in, it just loops once again.
Also when I put in a character then it just endlessly loops "Enter minimum number Enter maximum number" ignoring the cins. Anyone know why? I'm a beginner so this is probably really obvious
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int random(int minN, int maxN) //generates random number within specified range
{
srand (time(NULL));
int x = (maxN - minN);
int y = minN + (rand() % (x+1));
return y;
}
int require() //makes sure a < b and both are digits
{
int a,b;
do {
cout << "Enter minimum number" << endl;
cin >> a;
cout << "Enter maximum number. Note: Has to be greater or equal to minimum." << endl;
cin >> b;
} while (a > b || !isdigit(a) || !isdigit(b));
return random(a,b);
}
int main()
{
cout << require() << endl;
}
You should not use isdigit as this relates to a particular character is a digiti. Instead the loop should look like this:
int require() //makes sure a < b and both are digits
{
validNumbers = true;
do
{
cout << "Enter minimum number" << endl;
cin.clear();
cin >> a;
} while (cin.fail());
do
{
cout << "Enter maximum number. Note: Has to be greater or equal to minimum."
<< endl;
cin.clear();
cin >> b;
} while (cin.fail() || a > b);
return random(a,b);
}
PS: You only need to call srand (time(NULL)); once at the start of the program.
You are reading the numbers as, well, numbers not as characters as the isdigit function expects. If you are using a C++11 compliant standard library, the values of a and b will actually be zero if the input is not valid integer numbers, which means that e.g. !isdigit(a) will be true. If you are using a non-C++11 library, then the value of a and b will be random, and will most likely cause !isdigit(a) to be true as well as the amount of valid digit ASCII values in a full 32-bit integer range is quite small.
If you read a reference about the input operator, like this one you will see that if extraction fails, then the streams failbit will be set. This can either be tested "inline" like this:
if (!(std::cin >> a))
{
std::cout << "Not a valid number, try again: ";
continue;
}
Or it can be tested using the streams fail function.
I'm doing a problem where it asks to input an account number, which consists only of four digits. This has to be accomplished with basic beginner C++.
I need to figure out a way to restrict the input of the integer to four digits. A user should be able to put in 0043 or 9023 or 0001 and it should be an acceptable value....
I think I know how to accomplish it with a string.... getline(cin,input) and then check if input.length()==4?
But I've no idea how I would even do this with an integer input.
Note that if 0043 is intended to be distinct from 43, then the input is not in fact a number, but a digit string, just like a telephone "number".
Read the line as a string input.
Check that the length of input is 4.
Check that each character in the string is <= '9' and >= '0'.
Something like:
std::string read4DigitStringFromConsole()
{
bool ok = false;
std::string result;
while (!ok)
{
std::cin >> result;
if (result.length() == 4)
{
bool allDigits = true;
for(unsigned index = 0; index < 4; ++index)
{
allDigits = allDigits && (
(result[index] >= '0') &&
(result[index] <='9')
);
}
ok = allDigits;
}
}
return result;
}
Something like this should work. Once the user enters something with exactly four characters you can validate it. The rest of the logic is up to you.
#include <iostream>
#include <string>
int main() {
std::cout << "Enter a PIN Number: ";
std::string pinStr;
while(std::getline(std::cin,pinStr) && pinStr.size() != 4) {
std::cout << "Please enter a valid value\n";
}
}
Should you want to store it in an integer form, holding the integers in an std::vector might be beneficial. You can do this easily (loop unrolling was for clarity):
#include <iostream>
#include <string>
#include <vector>
int main() {
std::cout << "Enter a PIN Number: ";
std::string pinStr;
while(std::getline(std::cin,pinStr) && pinStr.size() != 4 ) {
std::cout << "Please enter a valid value\n";
}
std::vector<int> pin;
pin[0] = pinStr[0] - '0';
pin[1] = pinStr[1] - '0';
pin[2] = pinStr[2] - '0';
pin[3] = pinStr[3] - '0';
//pin now holds the integer value.
for(auto& i : pin)
std::cout << i << ' ';
}
You can see it running here
I like your idea to use a string as the input. This makes sense because an account "number" is simply an identifier. You don't use it in calculations. By if (sizeof(input)==4) I think you are trying to check the length of the string. The correct way to do this is if (input.length() == 4). This will check that the user inputs 4 characters. Now you need to make sure that each of the characters is also a digit. You can do this easily by taking advantage of the fact that the ASCII codes for digit characters are ordered as you expect. So if (input[i] >= '0' && input[i] <= '9') will do the trick with an appropriate for loop for the index i. Also, you probably need some kind of loop which continues to ask for input until the user enters something which is deemed to be correct.
Edit:
As an alternative to checking that each character is a digit, you can attempt to convert the string to an int with int value = atoi(input.c_str());. Then you can easily check if the int is a four-or-less-digit number.
// generic solution
int numDigits(int number)
{
int digits = 0;
if (number < 0) digits = 1; // remove this line if '-' counts as a digit
while (number) {
number /= 10;
digits++;
}
return digits;
}
similar to this post.
Then you can call this function to check if the input is 4 digits.
You probably want your code to be responsive to the user input, so I would suggest getting each character at a time instead of reading a string:
std::string fourDigits;
char currentDigit;
std::cout << "Enter 4 digits\n";
for(int i = 0; i < 4; ++i)
{
currentDigit = getch();
if(isdigit(currentDigit))
{
fourDigits += currentDigit;
std::cout << currentDigit; // getch won't display the input, if it was a PIN you could simply std::cout << "*";
}
else
{
// Here we reset the whole thing and let the user know he entered an invalid value
i = 0;
fourDigits = "";
std::cout << "Please enter only numeric values, enter 4 digits\n";
}
}
std::cout << "\nThe four digits: " << fourDigits.c_str();
This way you can handle gracefully invalid character instantly. When using strings, the input will only be validated once the user hits Enter.
So I was going over how I can use an integer type to get the input, and looked at char... since it's technically the smallest integer type, it can be used to get the code... I was able to come up with this, but it's definitely not refined yet (and I'm not sure if it can be):
int main() {
int count=0;
while(!(count==4)){
char digit;
cin.get(digit);
count++;
}
return 0;
}
So, the loop keeps going until 4 characters are collected. Well, in theory it should. But it doesn't work. It'll stop at 2 digits, 5 digits, etc.... I think it could be the nature of cin.get() grabbing white space, not sure.
Say I am looking to receive a series of numeric values and read them into an int, but I also want to test if the user hit key 'x'.
I am sure I am missing something obvious, and have tried a few things but seem to be stuck.
This is what I have so far...
cout << endl << "Enter key (or 'x' to exit): ";
cin >> key;
if (key == 'x') { cout << "exiting";}
// continue on...
You need to read into a string and then convert that to an integer. In outline:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
string s;
cout << endl << "Enter key (or 'x' to exit): ";
getline( cin, s );
if ( s == "x" ) {
// do exit stuff
}
else {
istringstream is( s );
int n;
if ( ! is >> n ) {
// report not an integer
}
else {
// do something with n
}
}
}
It depends on how key is declared.
If key is an int, you can only test for numbers, of course.
How about the following outline of an algorithm:
int n = 0
bool xentered = false
while (not xentered and there is one more character before EOF)
if that character is 'x' then xentered = true
else if it is a digit
n = 10*n + numeric value of the digit
else
error
I leave the task to translate that to the programming language of your choice. :)