How do you provide a condition in the if statement, if the variable is an integer data type then it will be displayed, and if the variable is any other data type then something else will be displayed?
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
using namespace std;
int main() {
char pilih,pilih2;
int p, l, a, t, r,ulang = 4;
float luas1, luas2, luas3, keliling1, keliling2, keliling3, phi = 3.14;
while (ulang > 0) {
pilihUlang:
cout << "Pilih jenis bangun datar berikut :\n 1. Persegi panjang\n 2. Segitiga sama sisi\n 3. Lingkaran" << endl;
cout << "Masukan pilihan anda [1/2/3] : ";
cin >> pilih;
system("cls");
switch (pilih) {
case '1':
system("color 07");
cout << "Luas Dan Keliling Persegi Panjang" << endl;
cout << "Masukan Panjang = ";
cin >> p;
if (?) { // <-- here
cout << "Masukan Lebar = ";
cin >> l;
system("cls");
cout << "Luas dan keliling Persegi Panjang dengan panjang " << p << " dan lebar " << l << ", yaitu :" << endl;
luas1 = p * l;
keliling1 = 2 * (p + l);
cout << "Luas = " << luas1 << endl;
cout << "Keliling = " << keliling1 << endl;
cout << "Sisa bisa memilih ulang " << ulang - 1 << " kali." << endl;
break;
}
else {
//...
}
From the istream::operator>> man page:
If extraction fails (e.g. if a letter was entered where a digit is
expected), zero is written to value and failbit is set.
So, your function could test the cin.good() method to see if the >> operation was successful, like this:
cin >> p;
if (cin.good()) {
cout << "The integer you typed was " << p << endl;
} else {
cout << "Hey, that wasn't an integer!" << endl;
}
Related
I have validated cin input by using std::numeric_limits and thus I need to include <limits>.
Will this effect the functionality of my Program?
I have been reading so many comments on different forums that using <limits> is not a good practice, but nobody cleared stated why it is not a good practice. If it is really a bad practice, what is a good practice to validate cin input for known errors, such as invalid inputs and long inputs?
#include <iostream>
#include <limits>
using namespace std;
void initMenu ();
void initDecision(int);
double areaCircle (double);
double areaRectangle (double, double);
const double PI = 4.14;
bool isValid (string);
int main()
{
int choice;
char cont;
do
{
system ("cls");
initMenu ();
while (!(cin >> choice))
{
cin.clear();
system ("cls");
initMenu();
cout << "---------------------------------------------------------------------------" << '\n';
cout << "Invalid Input cleared and turns to [" << cin.rdstate() << "] you can try it again or go to school" << '\n';
cout << "---------------------------------------------------------------------------" << '\n';
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
initDecision (choice);
do
{
cin.clear();
cout << "" << '\n';
cout << "------------------------------------------------" << '\n';
cout << "Do you want to continue using the Program? [Y/n]" << '\n';
cout << "------------------------------------------------" << '\n';
cin >> cont;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while (cont != 'Y' && cont != 'y' && cont != 'N' && cont != 'n' );
system ("cls");
cout << "-------------------------------" << '\n';
cout << "Thank you for using our Program" << '\n';
cout << "-------------------------------" << '\n';
}
while (cont == 'Y' || cont == 'y');
return 0;
}
void initMenu()
{
cout << "-------------------------------------------------" << '\n';
cout << "Choose any one option from above! [1] [2] [3] [4]" << '\n';
cout << "-------------------------------------------------" << '\n';
cout << "1 Circle" << '\n';
cout << "2 Rectangle" << '\n';
}
void initDecision(int choice)
{
double r, a, b, h;
switch (choice)
{
case 1:
cout << "Enter the Radius of a Circle: " << '\n';
do {cin >> r;} while (!isValid("Wrong Input detected, Try again!"));
areaCircle(r);
break;
case 2:
cout << "Enter Base and Height of a Rectangle: " << '\n';
do {cin >> b >> h;} while (!isValid("Wrong Input detected, Try again!"));
areaRectangle(b ,h);
break;
default:
cout << "----------------------------------------------------------------------" << '\n';
cout << "The option is out of bound, Check and try again with available options" << '\n';
cout << "----------------------------------------------------------------------" << '\n';
break;
}
}
double areaCircle (double r)
{
double result = PI * r * r;
cout << "The area of a circle that has value: [" << r << "] = [" << result << "]" << '\n';
return result;
}
double areaRectangle (double b, double h)
{
double result = b * h;
cout << "Rectangle with Base value: [" << b << "] and value of Height: [" << h << "] = [" << result << "]" << '\n';
return result;
}
bool isValid (string error_msg)
{
if(cin.rdstate())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max() , '\n');
system("cls");
initMenu();
cout << error_msg << '\n';
return false;
}
return true;
}
system("cls") doesnt work, it finishes the program without printing anything.
the program works without it but doesnt look nice in the console without all the previous prints cleared. I've tried putting the command in different places but it doesnt matter where i put it the program finishes instantly.
#include <iostream>
#include <math.h>
#include <windows.h>
#include <stdlib.h>
using namespace std;
float c, temp, eq;
char odp = 't';
int main()
{
do
{
cout << "Choose from what value you'd like to convert." << endl;
cout << "Celsius = 1 ; Fahrenheit = 0" << endl;
cin >> c;
if (c==1)
{
cout << "Insert Celsius value: ";
cin >> temp;
eq = temp * 1.8 + 32;
cout << "It is " << eq << " degrees Fahrenheit." << endl;
cout << "If you want to continue converting please insert: t" << endl;
cin >> odp;
}
else if (c==0)
{
cout << "Insert Fahrenheit value: ";
cin >> temp;
eq = (temp * 1.8) - 32;
cout << "It is " << eq << " degrees Celsius." << endl;
cout << "If you want to continue converting please insert: t" << endl;
cin >> odp;
}
else
{
cout << "Please choose correctly" << endl;
}
}
while(odp = 't');
return 0;
}
how i put the command and it finishes the whole program instantly
#include <iostream>
#include <math.h>
#include <windows.h>
#include <stdlib.h>
using namespace std;
float c, temp, eq;
char odp = 't';
int main()
{
do
{
cout << "Choose from what value you'd like to convert." << endl;
cout << "Celsius = 1 ; Fahrenheit = 0" << endl;
cin >> c;
if (c==1)
{ system("cls") //here
cout << "Insert Celsius value: ";
cin >> temp;
eq = temp * 1.8 + 32;
cout << "It is " << eq << " degrees Fahrenheit." << endl;
cout << "If you want to continue converting please insert: t" << endl;
cin >> odp;
}
else if (c==0)
{
cout << "Insert Fahrenheit value: ";
cin >> temp;
eq = (temp * 1.8) - 32;
cout << "It is " << eq << " degrees Celsius." << endl;
cout << "If you want to continue converting please insert: t" << endl;
cin >> odp;
}
else
{
cout << "Please choose correctly" << endl;
}
}
while(odp = 't');
return 0;
}
i really dont know, thanks for the replies
So, I have several fields to fill in with numerals. And if I try to fill in the input with letters (ex. 'noway' or 'gg1337' - it makes and error and asks for a valid number (without letters for ex. '13' or '1500000').
BUT there is one problem, if I start to fill the input with numbers and then I add some letters (for ex. '12nowshithappens'), this jumps to the next field of input, thinking it is a valid number, but showing an error in the next input field.
Here is the function code:
int appled()
{
cin >> appleds;
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "An arror occured!\nPlease, enter a valid number: ";
cin >> appleds;
}
return appleds;
}
If I described something wrong - here is the full code of my test program :)
// exZerry presents
#include <iostream>
#include <conio.h>
int apples;
int fruit;
int oranges;
int x;
int appleds;
int orangeds;
using std::cout;
using std::cin;
using std::endl;
using std::numeric_limits;
using std::streamsize;
char newline = '\n';
bool ok;
bool ok2;
bool ok3;
int appled() //Function to receive 'apples' input
{
cin >> appleds;
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "An arror occured!\nPlease, enter a valid number: ";
cin >> appleds;
}
return appleds;
}
int oranged() //Function to receive 'oranges' input
{
cin >> orangeds;
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "An arror occured!\nPlease, enter a valid number: ";
cin >> orangeds;
}
return orangeds;
}
int main()
{
ok = ok2 = ok3 = false; //Some testing
while(!ok2) //Actual program loop
{
x = 0; // Dropping program restart.
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
cout << "=====================================================" << endl;
cout << "Enter apples: ";
apples = appled();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n'); //Now we have apples
cout << "Enter oranges: ";
apples = oranged();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n'); //And now we have oranges
cout << "\n=====================================================" << endl;
cout << "Calculating..." << endl;
cout << "=====================================================" << endl;
fruit = apples + oranges;
cout << "In total we have " << fruit << " fruit" << endl;
cout << "=====================================================" << endl;
cout << newline;
//Option to go out or continue the loop
//If you enter 1 - resets the program, any other char - exit
cout << "Go out? (1 - 'No', Others - 'Yeap'):" << " ";
cin >> x;
cout << newline;
// ok2 = true;
if (x == 1)
{
cout << "Continue the program..." << endl;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
ok = false;
ok3 = false;
continue;
}
if (x == 0)
{
cout << "Shutting down the app..." << x << endl;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
break;
}
else
{
cout << "Shutting down the app..." << x << endl;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
break;
}
}
cout << "Press any key to exit :D" << endl;
getch();
return 0;
}
You can make your own facet that parses character sequence like that add invalid. Like this:
class num_get : public std::num_get<char>
{
public:
iter_type do_get( iter_type it, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, long& v) const
{
auto& ctype = std::use_facet<std::ctype<char>>(str.getloc());
it = std::num_get<char>::do_get(it, end, str, err, v);
if (it != end && !(err & std::ios_base::failbit)
&& ctype.is(ctype.alpha, *it))
err |= std::ios_base::failbit;
return it;
}
};
Now you can install it into your stream:
std::locale orig(std::cin.getloc());
std::cin.imbue(std::locale(orig, new num_get));
while (!(std::cin >> appleds)) {
// input was not entirely numeric
}
// input was entirely numeric
So I tried and it worked, thanks, Batmaaaan :D
Adding full working code. What's it doing? Simple: When you wish to count something and you obviously do not want to count letters in your program, this might help you to do it, while styding C++ or whatever. Some basics, I guess, for everyone =)
Made and tested in Visual Studio 2012. Took some time to gather every peace of code in one place.
// exZerry presents
// Apples & Oranges V2.1
#include <iostream>
#include <conio.h>
int apples;
int juce;
int oranges;
int x;
int appleds;
int orangeds;
using std::cout;
using std::cin;
using std::endl;
using std::numeric_limits;
using std::streamsize;
using std::locale;
char newline = '\n';
bool ok;
bool ok2;
bool ok3;
class num_get : public std::num_get<char>
{
public:
iter_type do_get( iter_type it, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, long& v) const
{
auto& ctype = std::use_facet<std::ctype<char>>(str.getloc());
it = std::num_get<char>::do_get(it, end, str, err, v);
if (it != end && !(err & std::ios_base::failbit)
&& ctype.is(ctype.alpha, *it))
err |= std::ios_base::failbit;
return it;
}
};
/*
int appled()
{
cin >> appleds;
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "An arror occured!\nPlease, enter a valid number: ";
cin >> appleds;
}
return appleds;
}
int oranged()
{
cin >> orangeds;
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "An arror occured!\nPlease, enter a valid number: ";
cin >> orangeds;
}
return orangeds;
}
*/
int main()
{
cout << "=====================================================" << endl;
cout << "Welcome to exZerry's 'Apples & Oranges V2'" << endl;
cout << "=====================================================" << endl;
cout << newline;
cout << newline;
ok = ok2 = ok3 = false;
while(!ok2)
{
x = 0;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
cout << "=====================================================" << endl;
cout << "Enter apples: ";
// apples = appled();
locale orig(cin.getloc());
cin.imbue(locale(orig, new num_get));
while (!(cin >> apples)) {
cout << "An arror occured!\nPlease, enter a valid number: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Enter oranges: ";
// oranges = oranged();
//std::locale orig(std::cin.getloc());
cin.imbue(locale(orig, new num_get));
while (!(cin >> oranges)) {
cout << "An arror occured!\nPlease, enter a valid number: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "\n=====================================================" << endl;
cout << "Calculating..." << endl;
cout << "=====================================================" << endl;
juce = apples + oranges;
cout << "In total we have " << juce << " fruit" << endl;
cout << "=====================================================" << endl;
cout << newline;
cout << "Go out? (1 - 'No', Others - 'Yeap'):" << " ";
cin >> x;
cout << newline;
// ok2 = true;
if (x == 1)
{
cout << "Continue the program..." << endl;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
ok = false;
ok3 = false;
continue;
}
if (x == 0)
{
cout << "Shutting down the app..." << x << endl;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
break;
}
else
{
cout << "Shutting down the app..." << x << endl;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
break;
}
}
cout << "Press any key to exit :D" << endl;
getch();
return 0;
}
I'm solving some C++ problems from ebooks. I made this C++ program but it isn't working properly. I've 2 problems:
Even after applying the forumla (votePercentage = firstAnswer/totalVotes*100;) it isn't showing the output, but only 0.
The program should display the bar chart, how am I suppose to do that? Any hints, reference or solution will be appreciated.
Here is my code:
/*
* Write a program that provides the option of tallying up the
* results of a poll with 3 possible values.
* The first input to the program is the poll question;
* the next three inputs are the possible answers.
* The first answer is indicated by 1, the second by 2, the third by 3.
* The answers are tallied until a 0 is entered.
* The program should then show the results of the poll—try making
* a bar graph that shows the results properly scaled to fit on
* your screen no matter how many results were entered.
*/
#include <iostream>
#include <string>
void startPoll (void);
void showPoll (void);
void pollCheck (void);
std::string pollQuestion, answer1, answer2, answer3;
int pollChoice, firstAnswer, secondAnswer, thirdAnswer;
int main (void)
{
int totalVotes = 1;
float votePercentage;
startPoll();
showPoll();
for(;;totalVotes++)
{
if (pollChoice == 1)
{
firstAnswer = firstAnswer + 1;
}
else if (pollChoice == 2)
{
secondAnswer++;
}
else if (pollChoice == 3)
{
thirdAnswer++;
}
else
{
std::cout << "==============*======*======*==============\n"
<< " RESULT \n"
<< "==============*======*======*==============\n"
<< "Question: " << pollQuestion << "\n"
<< "Total Votes: " << totalVotes << "\n";
votePercentage = (firstAnswer/totalVotes)*100;
std::cout << answer1 << ": " << firstAnswer << " votes. | " << votePercentage << "\n";
votePercentage = secondAnswer/totalVotes*100;
std::cout << answer2 << ": " << secondAnswer << " votes. | " << votePercentage << "\n";
votePercentage = thirdAnswer/totalVotes*100;
std::cout << answer3 << ": " << thirdAnswer << " votes. | " << votePercentage << "\n";
return 0;
}
std::cout << "\nEnter your vote again\nOR\nuse 0 to show the results.\n";
std::cin >> pollChoice;
}
std::cout << "Error: Something went wrong!\n";
}
void startPoll (void)
{
std::cout << "Enter your poll question:\n";
getline (std::cin, pollQuestion, '\n');
std::cout << "Enter answer 1:\n";
getline (std::cin, answer1, '\n');
std::cout << "Enter answer 2:\n";
getline (std::cin, answer2, '\n');
std::cout << "Enter answer 3:\n";
getline (std::cin, answer3, '\n');
}
void showPoll (void)
{
std::cout << "==============|======|======|==============\n"
<< " POLL \n"
<< "==============|======|======|==============\n"
<< pollQuestion << "\n"
<< "1. " << answer1 << "\n"
<< "2. " << answer2 << "\n"
<< "3. " << answer3 << "\n\n"
<< "Enter 1,2 or 3:\n\n";
std::cin >> pollChoice;
pollCheck();
}
void pollCheck (void)
{
if (pollChoice != 1 && pollChoice != 2 && pollChoice != 3)
{
std::cout << "Wrong choice entered! Please try again.\n\n";
return showPoll();
}
}
You need to take care that integer/integer = integer. In your case, changing
(firstAnswer/totalVotes)*100
to
(1.0*firstAnswer/totalVotes)*100
or
(firstAnswer*100.0/totalVotes)
should work. They all give a floating point result.
Well, the solution for the Bar Chart could be the following:(Not written by me) I think thats very self explaining because its really basic
void line (int n, char c)
{
// this is the loop for n
for (int i = 0; i < n; i++)
cout << c << endl;
}
Here is my solution, you can see how I made the bars work by reading the comments.
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 0;
int c = 0;
cout << "What is your favorite animal? 1 Cat, ";
cout <<"2 Dog, 3 Fish, 0 Count votes" << endl;
//Choice counter
while (true)
{
int choice;
cout << "Choice: ";
cin >> choice;
if(choice == 1)
a++;
else if(choice == 2)
b++;
else if(choice == 3)
c++;
else if(choice == 0)
break;
else
continue;
}
cout << endl << " 1: " << a << endl;
cout << " 2: " << b << endl;
cout << " 3: " << c << endl;
cout << endl << "1\t" << "2\t" << "3\t" << endl;
//Finds the max voted option
int max = 0;
if(a > b && a > c)
max = a;
else if(b > c && b > a)
max = b;
else if(c > a && c > b)
max = c;
/* If the max voted option is bigger than 10, find by how much
we have to divide to scale the graph, also making 10 bar
units the max a bar can reach before scaling the others too */
int div =2;
if(max > 10)
{
do
{
max = max/div;
if(max < 10)
break;
div++;
}while(true);
}else
div = 1;
//Sets the final number for the bars
a=a/div;
b=b/div;
c=c/div;
if(a==0)
a++;
if(b==0)
b++;
if(c==0)
c++;
//Creates the bars
while(true)
{
if(a>0)
{
cout << "[]" << "\t";
a--;
}else
cout << " ";
if(b>0)
{
cout << "[]" << "\t";
b--;
}else
cout << " ";
if(c>0)
{
cout << "[]" << "\t";
c--;
}else
cout << " ";
cout << endl;
if(a==0 && b==0 && c==0)
break;
}
}
I have an Addressbook C++ program that compiles and everything, but I cannot figure out how to write it to a file that saves the data each time it exits. Here is my code:
//AddressBook Program
#include <iostream>
#include <string.h>
#include <cstdlib>
#include <stdio.h>
using namespace std;
class AddressBook{
public :
AddressBook()
{
count = 0;
}
void AddEntry();
void DisplayAll();
void DisplayEntry(int i); // Displays one entry
void SearchEntry();
int MainMenu();
struct Entry_Struct
{
char firstName[ 15 ] ;
char lastName[ 15 ] ;
char birthday[ 15 ] ;
char phone[ 15 ] ;
char email[ 15 ] ;
};
Entry_Struct entries[100];
unsigned int count;
};
void AddressBook::AddEntry()
{
cout << "Entry number " << (count + 1) << " : " << endl;
cout << "Enter First Name: ";
cin >> entries[count].firstName;
cout << "Enter Last Name: ";
cin >> entries[count].lastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].phone;
cout << "Enter Email: ";
cin >> entries[count].email;
++count; // tally total entry count
}
void AddressBook::DisplayEntry(int i)
{
cout << "Entry[" << i + 1 << "] : " << endl; // states # of entry
cout << "First name : " << entries[i].firstName << endl;
cout << "Last name : " << entries[i].lastName << endl;
cout << "Date of birth : " << entries[i].birthday << endl;
cout << "Phone number : " << entries[i].phone << endl;
cout << "Email: " << entries[i].email << endl;
}
void AddressBook::DisplayAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DisplayEntry(i);
}
void AddressBook::SearchEntry()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].lastName) == 0)
{
cout << "Found ";
DisplayEntry(i);
cout << endl;
}
}
}
// Your class
AddressBook my_book;
int MainMenu()
{
int num;
bool bQuit = false;
// Put all your code into a while loop.
while(bQuit == false)
{
cout << "+-------------------------------------+" << endl;
cout << "| Address Book Menu |" << endl;
cout << "| |" << endl;
cout << "| 1- Add an entry |" << endl;
cout << "| 2- Search for an entry by last name |" << endl;
cout << "| 3- Display all entries |" << endl;
cout << "| 4- Exit |" << endl;
cout << "| |" << endl;
cout << "+-------------------------------------+" << endl;
cout << endl;
cout << "Please enter a number for one of the above options: ";
cin >> num;
cout << endl;
if (num == 1)
my_book.AddEntry();
else if (num == 2)
my_book.SearchEntry();
else if (num == 3)
my_book.DisplayAll();
else if (num == 4)
bQuit = true;
else
cout << "Invalid choice. Please try again" << endl;
cout << endl;
}
return 0;
}
int main (){
MainMenu();
return 0;
}
I've gone over my textbook all day and nothing I'm doing is working.
Here is a basic example of opening, and writing an output file,
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream outfile;
outfile.open ("addressbook.txt");
outfile << "Daffy,Duck,123 Main Street,Anytown,OH,USA,123-456-7890\n";
myfile.close();
return 0;
}
You need to have an inserter for your class. It's done using operator <<:
// Inside your class:
friend std::istream& operator<<(std::ostream& os, const AddressBook ab)
{
return os << /* ... */
}
As you can see, a user-defined operator << can be implemented in terms of the pre-defined standard inserter. You can use it in the following way:
std::ifstream in("yourtxtfile.txt");
in << my_book;