check if my variable is not integer in "if" statement in c++ - c++

I have written c++ code and this is part of it:
int flag8=1,
tmp,
part;
.
.
.
if(part > 7 || !(int)tmp || tmp < 0){
cout << "ERROR !!!\n";
flag8=0;
break;
}
how can I check my tmp variable is integer or not?
I want to say my if statement be true if part>7 or tmp is not integer or tmp<0.
thank you very much.
edit:
this is my whole code:
#include <iostream>
using namespace std;
int base2toten(int nums);
int base8toten(int num);
////////////////////////////////////////////
/* FUNCTION: CONVERTING BASE 2 TO 10 */
////////////////////////////////////////////
int base2to10(int nums){
int base2,
digits,
base10=0,
parts,
powers=1,
flag2=1;
cout << "Enter num base 2: ";
cin >> base2;
//if(!(int)base2 && base2 < 0 || !(int)base2 && base2 > 1){
// cout << "OUT OF RANGE"
//}
digits = base2;
while(digits){
parts = digits % 10;
if(parts > 1 || !(int)base2 || base2 < 0){
cout << "The number you have entered is not base 2 !!!\n";
flag2=0;
break;
}
digits /= 10;
base10 += powers * parts;
powers *= 2;
}
if(flag2){
cout << " \"base2\":\t" << base2 << "\n"
<< "\"base10\":\t" << base10 << endl;
}
}
///////////////////////////////////////////
/* FUNCTION: CONVERTING BASE 8 TO 10 */
///////////////////////////////////////////
int base8to10(int num){
int base8,
digit,
base10=0,
part,
power=1,
flag8=1;
cout << "Enter num base 8: ";
cin >> base8;
digit = base8;
while(digit){
part = digit % 10;
if(part > 7 || !(int)(base8) || base8 < 0){
cout << "The number you have entered is not base 8 !!!\n";
flag8=0;
break;
}
digit /= 10;
base10 += power * part;
power *= 8;
}
if(flag8){
cout << "\"base8\":\t" << base8 << "\n"
<< "\"base10\":\t" << base10 << endl;
}
}
//////////////////////////////////////////
/* FUNCTION: MAIN */
//////////////////////////////////////////
int main(){
int num,nums,a ,b,ans;
// cout << "What base you want to convert?\n"
cout << "*******************************************************\n"
<< "* BASE TWO: 2 *\n"
<< "* BASE EIGHT: 8 *\n"
<< "* BOTH BASE TWO AND EIGHT: 28 *\n"
<< "* BOTH BASE EIGHT AND TWO: 82 *\n"
<< "*******************************************************\n";
cout << "What base you want to convert? ";
cin >> ans;
if(ans != 2 && ans != 8 && ans != 28 && ans !=82){
cout << "Your answer in not acceptable!!!\n";
}
else if(ans == 2){
cout << "**********************************\n"
<< "* YOU'VE CHOSEN BASE 2 *\n"
<< "**********************************\n";
base2to10(a);
}
else if(ans == 8){
cout << "**********************************\n"
<< "* YOU'VE CHOSEN BASE 8 *\n"
<< "**********************************\n";
base8to10(b);
}
else if(ans == 28){
cout << "*********************************************\n"
<< "* YOU'VE CHOSEN BOTH BASE 2 AND 8 *\n"
<< "*********************************************\n";
base2to10(a);
base8to10(b);
}
else if(ans == 82){
cout << "*********************************************\n"
<< "* YOU'VE CHOSEN BOTH BASE 8 AND 2 *\n"
<< "*********************************************\n";
base8to10(b);
base2to10(a);
}
return 0;
}

Your question very likely asks for an XY-Problem. Since C++ is a typed language, the type you have used to declare a variable will always stay the same.
You'll need to check the state of your input stream, to test if the input was given in the correct format:
int tmp;
std::cin >> tmp;
if(!cin)
{
// user input was not parsable as integer value ...
}
If you want to specify particular numeric input formats, you can use stream manipulators (need to #include <iomanip>):
std::cin >> std::oct >> tmp; // Will parse integer from base 8 input
std::cin >> std::hex >> tmp; // Will parse integer from base 16 input

This is an example of what you want...Hope this helps...
This is only an example and you may have to check thoroughly and modify before using it in a real world app..
#include<stdio.h>
int main(){
int n=0;
char c;
do{
c=getchar();
if(c>='0' && c<='9'){
n=n*10;
n+=(c-48);
}
else if(c=='\n'){
break;
}
else{
printf("SOME THING WRONG");
break;
}
}while(1);
printf("%d ",n);
return 0;
}
Since you are saying base8 (from 0 to 7) modify the if statement with if(c>='0' && c<='7')

Related

Program to calculate test scores [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I am writing a program to calculate the grade of 3 test scores. The lowest of the first 2 scores is dropped and added to the third test score to make the final grade. The 3 test scores cannot be higer than 50, lower than 0 and cannot be a character or string. So far, I have satisified all those requirment but I need to implement decimal grades to the program like for instance 45.5. Also to round the final grade up or down. For example if final grade is 89.5 round up to an A.
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
char getGrade(int num) {
if (num < 60)
return 'F';
if (num < 69)
return 'D';
if (num < 79)
return 'C';
if (num < 89)
return 'B';
return 'A';
}
bool isnumeric(string temp) {
for (char &chr : temp) {
if ((chr >= '0' and chr <= '9') or chr == '-')
continue;
else
return false;
}
return true;
}
int main(int argc, char const *argv[]) {
cout << "Welcome to the grade calculator.You will input three test "
"scores.\nThe highest of the first two grades and the third grade "
"will be\nadded together to determine the numeric grade average for "
"the\ncourse.Each test score has a maximum of 50 points.\n";
int arr[3];
int ctr = 0;
string temp;
int num;
while (ctr < 3) {
cout << "\nPlease enter test score " << (ctr + 1) << ": ";
label1:
cin >> temp;
if (isnumeric(temp)) {
num = atoi(temp.c_str());
if (num > 50) {
cout << "\nTest scores cannot be higher than 50, try again: ";
goto label1;
} else if (num < 0) {
cout << "\nTest scores cannot be negative, try again: ";
goto label1;
} else {
arr[ctr++] = num;
}
} else {
cout << "\nInvalid test score entered, try again: ";
goto label1;
}
}
int average = 0;
average = max(arr[0], arr[1]);
average = average + arr[2];
cout << "\nThe average for the course = " << average << "\n";
cout << "The letter grade = " << getGrade(average);
cout << "\n\n\nThank you for using this program\n";
return 0;
}
Just changed a couple of things to make it work with decimals:
1. Added chr == '.' to the isNumeric() function:
bool isnumeric(string temp) {
for (char& chr : temp) {
if ((chr >= '0' and chr <= '9') or chr == '-' or chr == '.')
continue;
else return false;
}
return true;
}
2. Changed variable types:
double arr[3]{};
int ctr = 0;
std::string temp;
double num;
3. Removed goto: (You can just use continue)
while (ctr < 3) {
std::cout << "\nPlease enter test score " << (ctr + 1) << ": ";
std::cin >> temp;
if (isnumeric(temp)) {
num = atof(temp.c_str());
if (num > 50) {
std::cout << "\nTest scores cannot be higher than 50, try again: ";
continue;
}
else if (num < 0) {
std::cout << "\nTest scores cannot be negative, try again: ";
continue;
}
else {
arr[ctr++] = num;
}
}
else {
std::cout << "\nInvalid test score entered, try again: ";
continue;
}
}
4. For rounding off, you can use std::round() as such:
double average = 0;
average = std::max(arr[0], arr[1]);
average = std::round(average + arr[2]);
You can also change your cout statements:
std::cout << "\nThe average for the course = " << average;
if (std::round(average) != average) std::cout << ", rounded off to = " << std::round(average);
std::cout << ".\nThe letter grade = " << getGrade(average);
std::cout << "\n\n\nThank you for using this program\n";
Just make all these changes and your program will successfully work with decimals.
Also, consider not using the following in your code:
using namespace std;
..as it's considered as a bad practice. For more info on why, look up to Why is using namespace std considered as a bad practice.
Edit: To accomplish your requirement, you can just change the while loop as such:
while (ctr < 3) {
if (temp.size() == 0)
{
std::cout << "\nPlease enter test score " << (ctr + 1) << ": ";
std::cin >> temp;
}
if (isnumeric(temp)) {
num = atof(temp.c_str());
if (num > 50) {
std::cout << "\nTest scores cannot be higher than 50, try again: ";
std::cin >> temp;
continue;
}
else if (num < 0) {
std::cout << "\nTest scores cannot be negative, try again: ";
std::cin >> temp;
continue;
}
else {
arr[ctr++] = num;
temp.clear();
}
}
else {
std::cout << "\nInvalid test score entered, try again: ";
std::cin >> temp;
continue;
}
}
The above code works as you said.

To confirm only 1 and 0 exist in the Binary

I wanted to use only 1 and 0 for the binary. But instead the answer keep giving me the 2nd option with whatever number I typed. I had tried where did I programmed wrongly but unfortunately I still can't find it. So I hoped that I could get some help here.
#include<iostream>
#include<cmath>
using namespace std;
int DualzahlZuDezimal(long long n)
{
int dez = 0;
int i = 0, rem;
while (n != 0)
{
rem = n % 10;
n /= 10;
dez += rem * pow(2, i);
++i;
}
return dez;
}
string a;
int main()
{
long long n;
int dez;
cout << "Test Ein- und Ausgabe : \n";
cout << "----------------------- \n";
cout << "Eingabe einer Dualzahl : ";
cin >> n;
if ((n == '1') && (n == '0'))
{
cout << "Dual : " << n << endl;
cout << "Dezimal : " << DualzahlZuDezimal(n) << endl;
cout << "cin ok ? : ja-ok" << endl;
return 0;
}
else
{
cout << "Dual : 0" << endl;
cout << "Dezimal : 0" << endl;
cout << "cin ok ? : nein-nicht ok" << endl;
return 0;
}
}
If I understand this right, you want the user to enter a binary number, like 10001101001, and you will show the decimal equivalent (1129 in this case).
There are 2 general ways to do that yourself:
You can read the value as a number, as you do, and then apply your conversion
process, except that you check that rem is either 0 (in which case you do
nothing), or 1 (in which case you add the power of 2). If it's another value,
you report the error, and return 0.
You can read the value as a std::string instead. Then you can use
std::find_first_not_of()
to check for contents other than 0 or 1:
if (n.find_first_not_of("01") != string::npos) { /* complain */ }
but then you need to do the conversion based on characters.
But the best approach is not to reinvent the wheel and instead let the standard library handle it for you via stol():
#include <cstddef>
#include <iostream>
#include <string>
using namespace std;
int
main()
{
string text;
cout << "Enter a binary number: " << flush;
cin >> text;
size_t endpos = 0;
long decimal_number = stol(text, &endpos, 2); // base 2 == binary
if (endpos != text.size()) {
cerr << "'" << text << "' is not a valid binary number!" << endl;
return 1;
}
else {
cerr << "binary number: " << text << endl;
cerr << "decimal number: " << decimal_number << endl;
return 0;
}
}
Keep in mind that input from the console is text. If you need to check that the text matches a particular format (in this case, consists entirely of 1's and 0's), the simplest approach is to look at that text:
std::string input;
std::cin >> input;
bool input_is_valid = true;
for (int i = 0; input_is_valid && i < input.length(); ++i) {
if (input[i] != '0' && input[i] != '1')
input_is_valid = false;
}
then, if the input is valid, convert the text to a numeric value:
long long n = std::stoll(input);

why if statement with and condition is not working as expected?

The similar question is not what I asking.
Here,
#include <iostream>
using namespace std;
int main(){
int base, inputX;
int aCounter = 0;
do {
std::cout << "Please enter a value between 1-10" << endl;
std::cin >> inputX;
if (!cin) {
std::cout << "Error! number only" << endl;
std::cin.clear();
std::cin.ignore(100, '\n');
}else if (inputX <= 0 && inputX > 18) {
std::cout << "Error! please enter a correct number" << endl;
}else{
base = inputX;
std:;cout << "The number for base is " << base << "." << endl;
aCounter++ ;
}
}while (aCounter == 0);
}
If I input other than number, it loop again and run well.
If I input a number even is 0 or negative, it straight end the loop and print the else statement, what happen to else if?
I think you want to to use or instead of and in else if (inputX <= 0 && inputX > 18)
It will check else if if your code like this:
else if (inputX <= 0 || inputX > 18)

How can I take specific user inputs in an array?

I am coding a program that converts a binary number into decimal number by doubling (link to wikihow article).
If the user input is something other than 1 or 0, then its not a binary number, under that circumstance I want the loop to "break" and say something like:
"Oops! Binary numbers have only 1 or 0".
If not "then" the loop should continue.
That is I want to code something like
for(int digits = 0; digits != digitsINbinNum; ++digits){
if(a condition that checks if user input is anything else than 1 or 0){
coût << ""Oops! Binary numbers have only 1 or 0" << endl;
break;
}else{
cin >> binArray[digits];/*<-----------Here's the part where I am trying to do that*/
}
}
Refer to the code given below for more info:
#include <iostream>
#include <iterator>
using namespace std;
int main(){
int digitsINbinNum;
cout << "If you don't mind. Please enter the number of digits in your binary number: ";
cin >> digitsINbinNum;
int binArray[digitsINbinNum];
cout << "Enter the binary number: ";
for(int digits = 0; digits != digitsINbinNum; ++digits){
cin >> binArray[digits];/*<-----------Here's the part where I am trying to do that*/
}
/*using the doubling method as found in wikihow.com*/
int total = 0;
for(int posiOFdigit = 0; posiOFdigit != sizeof(binNum[noOFdigits]); posiOFdigit++){
total = total * 2 + binNum[posiOFdigit];
}
/*Printing the number*/
cout << "Decimal form of ";
for(int n = 0; n != noOFdigits; n++){
cout << binNum[n];
}
cout << " is " << total;
return 0;
}
The logic for converting a binary number into decimal number by the doubling method can be referred from the given link in the question.
Modifying the given code to keep it as close as possible to the question's reference code.
Note: As ISO C++ forbids variable length array, I am changing
int binArray[digits] to
int *binArray = (int *)malloc(sizeof(int) * digitsINbinNum);.
This modification makes it an integer pointer and it gets the memory of required size allocated at runtime.
#include <iostream>
using namespace std;
int main(){
int digitsINbinNum,
/* variable to keep decimal conversion of given binary */
decimal_val = 0;
bool is_binary = true;
cout << "If you don't mind. Please enter the number of digits in your binary number: ";
cin >> digitsINbinNum;
/*
ISO C++ forbids variable length array,
making it int pointer and allocating dynamic memory
*/
int *binArray = (int *)malloc(sizeof(int) * digitsINbinNum);
if (binArray == NULL)
{
cout << "Memory allocation failure" << endl;
exit -1;
}
cout << "Enter the binary number: ";
for(int digits = 0; digits != digitsINbinNum; ++digits){
cin >> binArray[digits];
/*<-----------Here's the part where I am trying to do that*/
/* doubling method logic for conversion of given binary to decimal */
if ((binArray[digits] == 0) ||
(binArray[digits] == 1))
{
decimal_val = (decimal_val * 2) + binArray[digits];
}
else /* not a binary number */
{
is_binary = false;
cout << "Oops! Binary numbers have only 1 or 0" << endl;
break;
}
}
/* if conversion is successful: print result */
if (is_binary)
{
cout << "Decimal Value for given binary is: " << decimal_val << endl;
}
if (binArray)
{
free(binArray);
}
return 0;
}
You don't need an array for this. Here is a simple solution:
#include <iostream>
int main(){
int digitsINbinNum;
std::cout << "If you don't mind. Please enter the number of digits in your binary number: ";
std::cin >> digitsINbinNum;
std::cout << "Enter the binary number: ";
int ret = 0;
for(int digits = 0; digits != digitsINbinNum; ++digits) {
int bin;
std::cin >> bin;
if (bin == 1 || bin == 0) {
ret = 2 * ret + bin;
} else {
std::cout << "Oops! Binary numbers have only 1 or 0" << std::endl;
return -1;
}
}
std::cout << ret << std::endl;
return 0;
}

Counting digits in a number without using strings

i have the next code which asks the user for a really long number like 100000000 and then it prints how many times a given digit appears on that number, the code works fine and does everything correctly, but the professor told me that i dont have to use strings or chars, but when the code asks the user for a number it necessarily needs a string and i don´t know how to modify it, i used the gmp library
#include <iostream>
#include <stdio.h>
#include <gmp.h>
#define MAX 40
using namespace std;
void searchDigit(FILE *fd);
int NewNumber();
int main()
{
FILE *fd;
int otherNumber;
string text;
mpz_t num;
do
{
if((fd = fopen("File.txt","w+"))!= NULL)
{
mpz_init(num);
cout << "Give me the number: " << endl;
cin >> text;
mpz_set_str(num,text.c_str(),10);
mpz_out_str(fd,10,num);
fclose(fd);
searchDigit(fd);
otherNumber = NewNumber();
}
else
cout << "Fail!!" << endl;
}while(otherNumber);
return 0;
}
void searchDigit(FILE *fd)
{
int car,continue = 1,r;
char answer,digit;
if((fd = fopen("File.txt","r"))!= NULL)
{
do
{
r = 0;
fseek(fd,0,SEEK_SET);
cout << "What digit do you want to search? " << endl;
cin >> digit;
while((car = fgetc(fd))!= EOF)
{
if(car == digit)
r++;
}
cout << "The digit x=" <<digit<< " appears " << r << " times" << endl;
cout << "Do you want to search any other digit? " << endl;
cin >> answer;
if(answer != 'S')
continue = 0;
}while(continue);
}
else
cout << "Fail!!" << endl;
}
int NewNumber()
{
char answer;
cout << "DO you wish to work with a new number? " << endl;
cin >> answer;
if(answer == 'S' || answer == 's')
return 1;
else
return 0;
}
Thanks in advance
Depends on how big your input might actually be... but for retrieving digits you could do something like:
#include <iostream>
using namespace std;
typedef unsigned long long UINT64;
int main() {
UINT64 i;
std::cin >> i;
while (i >= 1) {
int digit = i % 10;
std::cout << digit << " ";
i /= 10;
}
}
input: 18446744073709551614
outputs: 4 1 6 1 5 5 9 0 7 3 7 0 4 4 7 6 4 4 8 1