getting numbers only for cin - c++

trying to make a function that reliably and safely ask the user for the three
components of a date – the day, the month & the year... i can get it to ask for the date... however i need to be able to make it so that you can only input numbers only, no letters and no mix of letters and numbers...
#include <iostream>
using namespace std;
int Day;
int Month;
int Year;
int GetYear(){
cout << "Enter a Year > ";
int nYear;
cin >> nYear;
cout << "Year: ";
Year = nYear;
return nYear;
}
int GetMonth(){
cout << "\nEnter a Month > ";
int nMonth;
cin >> nMonth;
cout << "Month: ";
Month = nMonth;
return nMonth;
}
int GetDay(int nMonth, int nYear){
cout << "\nEnter a Day > ";
int nDay;
cin >> nDay;
cout << "Day: ";
Day = nDay;
return nDay;
}
bool GetDate(int nDay, int nMonth, int nYear){
cout << "\nDate: ";
cout << nDay << "/" << nMonth << "/" << nYear << "\n";
return 0; //GetDate(Day, Month, Year);
}
void main() {
cout << GetYear();
cout << GetMonth();
cout << GetDay(Month, Year);
cout << GetDate(Day, Month, Year);
cout <<"Press Enter Key To Exist...";
cin.ignore (numeric_limits<streamsize>::max(), '\n' );
cin.get();
}

Maybe not a proper way...
I use that in my school homework.
#include <iostream>
#include <stdio.h>
#include <conio.h>
int getInputNumber()
{
int key;
do
{
key = _getch();
}while (key < '0' || key > '9');
std::cout << key - '0';
return key - '0';
}
int main()
{
int n = getInputNumber() ;
system("pause");
return 0;
}
Also,just in windows
You need to write your own function,than you could input a number bigger than 9.

On a general note: It's not possible
When you invoke a program and use a shell (or a CMD prompt on windows) interface for taking inputs, all the input handling is done by the shell interface and it is not advisable to fiddle with it to accept only the required set of characters, because the shell is common for all the programs on your machine.
This is technically possible by implementing your own shell and replacing it with the default system shell, but let's not discuss it here and you should not do it :)
The best you can do is to verify the input for valid numbers. A simple ASCII value check will do it for you. You can also use some utility functions like atoi or strtoul to skip the invalid characters in the given input and just use the consecutive numeric digits.

Related

how to fix: no operator matches these operands

I do not understand why these errors exist about the operands. I also am curious, when I print out "Your bill is...", how do I allow the computer to calculate the bill for me?
Your error is because you are trying to compare an int to a string, which won't work, that comparison is not defined. Besides, your string is empty anyway.
Also, your if has an erroneous ; on the end of it. In fact, your whole if makes no sense and should be removed.
Try this instead:
#inslude <iostream>
using namespace std;
int main()
{
int TDU, kWh;
cout << "Who is your TDU?\n";
cin >> TDU;
cout << "How many kWh did you use for the month you would like to calculate?\n";
cin >> kWh;
cout << "Your bill is " << 3.42 + (0.0384470 * kWh);
return 0;
}
UPDATE: That being said, you probably meant to do something more like this instead:
#inslude <iostream>
using namespace std;
static const int ONCOR = ...; // <-- for you to fill in as needed...
int main()
{
int TDU, kWh;
cout << "Who is your TDU?\n";
cin >> TDU;
cout << "How many kWh did you use for the month you would like to calculate?\n";
cin >> kWh;
if (TDU == ONCOR)
cout << "Your bill is " << 3.42 + (0.0384470 * kWh);
return 0;
}
Alternatively:
#inslude <iostream>
using namespace std;
int main()
{
string TDU;
int kWh;
cout << "Who is your TDU?\n";
cin >> TDU;
cout << "How many kWh did you use for the month you would like to calculate?\n";
cin >> kWh;
if (TDU == "ONCOR")
cout << "Your bill is " << 3.42 + (0.0384470 * kWh);
return 0;
}
Depending on what format you want the user to enter the TDU as.

I keep getting a variable uninitialized error when calling a function that is asking for user input

#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int numofEmployees();
int daysMissed(int);
int AverageMissed(int, int);
int main()
{
cout << "Welcome to employee absentee calculator!" << endl;
int numEmployees = numofEmployees();
int Missed = daysMissed(numEmployees);
double misAverage = AverageMissed(numEmployees, Missed);
cout << "There are " << numEmployees << " in the company. They have missed " << Missed << " days total. On average, they have missed " << misAverage << " days." << endl;
return 0;
}
int numofEmployees() {
cout << "How many employees are in your company? ";
int employees;
cin >> employees;
while (employees < 1) {
cout << "Employee count must 1 or greater!" << endl;
}
return employees;
}
int daysMissed(int numEmployees) {
int Absence, totAbsence = 0;
for (int i = numEmployees; i < numEmployees; i++) {
cout << "How many days has each employee missed this passed year? ";
cin >> Absence;
totAbsence += Absence;
}
while (Absence < 0) {
cout << "Values entered must be positive numbers!" << endl;
cin >> Absence;
}
return totAbsence;
}
int AverageMissed(int numEmployees, int Missed){
double Average;
Average = double(numEmployees) / double(Missed);
return Average;
}
This code is being used to calculate the average number of employee absences by way of using three functions. The second function is not working correctly as it is not being called properly by the main. This is for a school assignment.
The problem is daysMissed - if numEmployees is <= 0, then Absense will be uninitialized. But, you say, "I check that in numofEmployees" - the problem is that the compiler doesn't do that sort of whole-program analysis before issuing these warnings.
There is another problem: daysMissed is wrong (twice). If there are two employees, and I enter -2 and 1, there will be no error for the negative number. If on the other hand, if I enter 1 and -2, you never correct totAbsence. You would be much better off writing a little function which reads a number >= some limit in a loop, and keeps prompting until given the correct value. Something like:
int read(const char* prompt, const char* err_prompt, int limit) {
cout << prompt << endl;
for(;;) {
int result;
cin >> result;
if (result >= limit) {
return result;
}
cout << err_prompt << endl;
}
}
Then daysMissed becomes much pleasanter to write - and you can use the same function to read the number of employees (which will go into an infinite loop at the moment)
You should also validate a division by zero plus change the return type.
double AverageMissed(int numEmployees, int Missed){
if (Missed > 0) return double(numEmployees) / Missed;
return 0;
}
by the way, there is no need to cast both operands in the division (/). Casting one of them will be enough to return a double type.

Cannot get my getchar() function to work how I want it to work, output is10 not 2 c++

I cannot figure out why my getchar() function is not working the way I want it to work. I am getting 10 not 2. Please take a look.
Main():
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int var, newvar;
cout << "enter a number:" << endl;
cin >> var;
newvar = getchar();
cout << newvar;
return 0;
}
Here is my output:
enter a number:
220
10
Ultimately though I need to be able to distinguish between a '+' '-' or letter or number.
This is maybe not the cleanest way to do it but you can get every char one by one :
#include <iostream>
using namespace std;
int main()
{
int var;
cout << "enter a number:" << endl;
cin >> var;
std::string str = to_string(var);
for(int i=0; i < str.length();++i)
cout << str.c_str()[i] << endl;
return 0;
}
If you enter for example: "250e5" it will get only 250 and skip the last 5.
Edit:
This is just a simple parser and does not do any logic.
If you want to make a calculator I would recommend you to look at what Stroustrup did in his book the c++ programming language.
int main()
{
string str;
cout << "enter a number:" << endl;
cin >> str;
for(int i=0; i < str.length();++i) {
char c = str.c_str()[i];
if(c >= '0' && c <= '9') {
int number = c - '0';
cout << number << endl;
}
else if(c == '+') {
// do what you want with +
cout << "got a +" << endl;
} else if(c == '-')
{
// do what you want with -
cout << "got a -" << endl;
}
}
return 0;
}

C++ currency conversion code

Hi I'm new with c++ and am having a hard time with creating a code to convert currencies. Could you please look at my current code and give any suggestions. the first goal is first to determine the type of currency. then the amount. finally the conversion.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declaring constant conversion values of currency per dollar
const float ColombianPeso = 2000;
const float MexicanPeso = 13.25;
const float ArgentinePeso = 8.4;
const float VenesuelanBolivar = 6.28;
const float ChileanPeso = 593.719;
//designing statement to allow user to input curency type
char currency[] = "show me the money (USDollar, MexicanPeso, ArgentinePeso, ColombianPeso, VenesuelanBolivar, or ChileanPeso):\n";
char answer1[17];
cout << currency;
cin >> answer1;
//designing statement to imput amount
float amount = 0;
cout << "enter amount:\n";
cin >> amount;
//creating if/else statement to convert for diffent money values
if (answer1 == USDollar)
cout << "number of Colombian Pesos:\n" << amount * ColombianPeso;
cout << "number of Venesuelan Bolivars:\n" << amount * VenesuelanBolivar;
cout << "number of Mexican Pesos:\n" << amount * MexicanPeso;
cout << "number of Argentine Pesos:\n" << amount * ArgentinePeso;
cout << "number of Chilean Pesos:\n" << amount * ChileanPeso;
else if (answer1 == MexicanPeso)
cout << "number of US Dollars:\n" << amount / MexicanPeso;
else if (answer1 == ColombianPeso)
cout << "number of US Dollars:\n" << amount / ColombianPeso;
else if (answer1 == ArgentinePeso)
cout << "number of US Dollars:\n" << amount / ArgentinePeso;
else if (answer1 == ChileanPeso)
cout << "number of US Dollars:\n" << amount / ChileanPeso;
else if (answer1 == VenesuelanBolivar)
cout << "number of US Dollars:\n" << amount / VenesuelanBolivar;
else
cout << "try again with VenesuelanBolivar, USDollar, ChileanPeso, ArgentinePeso, ColombianPeso, or MexicanPeso:\n";
return 0;
}
Use a std::string instead of char[]. Also you need to compare to string literals, otherwise it will think those are variables.
std::string answer1;
cin >> answer1;
if (answer1 == "USDollar")
{
// do stuff
}
You're comparing char[] and float, I think you don't want it.
const float ColombianPeso = 2000;
//...
char answer1[17];
//...
cin >> answer1;
//...
else if (answer1 == ColombianPeso)
I'd recommend you to use std::unordered_map; it allows you to in example get float used to conversion when you give a string. Also, it allows modify currency and their ratio in runtime.
#include <string>
#include <unordered_map>
#include <iostream>
#include <stdexcept>
using std::cout;
using std::cin;
using std::clog;
int main(){
std::unordered_map<std::string, float> ratio{
{"ColombianPeso", 2000},
{"MexicanPeso", 13.45},
{"ArgentinePeso", 8.4},
{"VenesueleanBolivar", 6.28},
{"ChileanPeso", 593.719}
};
clog << "Available currency:\n";
for(auto it=ratio.cbegin(); it!=ratio.cend(); ++i)
clog<< '\t' << it->first << ' ' << it->second << '\n';
clog << "Pick one of currency above: ";
std::string choice;
cin >> choice;
try{
auto value=ratio.at(choice); /*if element doesn't exist,
program jumps to the catch*/
float amount;
clog >> "Enter amount: ";
cin >> amount;
cout << value*amount << '\n';
}catch(std::out_of_range&){
clog << "Given currency is not available.\n";
}
}

Currency Conversion Program

I'm working on a currency converter program that converts the old system of British pounds, Shillings, and pence, into their new system, which is a type of Decimal Pound. Where 100 pence equals a pound. Here is the code for the program
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
int calcNum(int pound, int shilling, int pence)
{
pence = pound*240 + shilling*12 + pence;
return pence;
}
int calcNew(int total_pence, double dec_pound)
{
dec_pound = total_pence / 240;
return dec_pound;
}
int main()
{
int pence;
int shilling;
int pound;
const int OLD_POUND = 240;
const int OLD_SHILLING = 12;
double total_pence;
double dec_pound = 0;
double deci_pound;
cout << "Please Enter the Amount of old pounds: ";
cin >> pound;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old shillings: ";
cin >> shilling;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old pence: ";
cin >> pence;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);
cout << (5, "\n");
cout << "The total amount in decimal pounds is: ";
cout << setprecision(2) << "\x9c" << deci_pound;
_getch();
return 0;
}
When I run this program however, I'm having a bit of a problem. No matter what the number input is, it always says 0 pounds. Just to make sure that the setprecision function at the end wasn't interfering with the code, I had originally set a cout statement with a _getch() after the two functions to show how much deci_pound came out to be calculated to, and once again, it came out as zero. So my issue seems to be somewhere in the functions running the calculations. If someone could help me with this, I would really appreciate it.
Your calcNew(...) function returns an int, make it return a double. Right now it casts to int which involves stripping the decimals.
In your code, dec_pound is set equal to zero, and you're deci_pound = calcNew(dec_pound, total_pence), which divides 0 by 240 = 0.
The order of the parameters when you call both functions is wrong. Your functions are declared and implemented as:
int calcNum(int pound, int shilling, int pence);
int calcNew(int total_pence, double dec_pound);
And then you call them like this:
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);