To confirm only 1 and 0 exist in the Binary - c++

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);

Related

How to Print the invalid input in a error message? C++

The Idea is to invoke a single function to check the user input and return True || False.
User Input with 0123456789 must return
The Number Entered Correctly
User Input with 0123w456789 must return
Number is not allowed or Contains invalid input such as "w"
User Input with 0123wx456789 must return
Number is not allowed or Contains invalid input such as "wx"
My Code:
#include <iostream>
using namespace std;
int main ( )
{
string i_numvalidation;
cout << "Enter the number: " << '\n';
cin >> i_numvalidation;
bool isNumber = true;
for (int i = 0; i < i_numvalidation.length(); i++)
{
if (!(i_numvalidation[i] >= '0' && i_numvalidation [i] <= '9'))
{
isNumber = false;
}
}
if (isNumber)
cout << " Entered number " << i_numvalidation << " is correct" << '\n';
else
cout << " Entered number " << i_numvalidation << " is not allowed or Contains invalid input such as " << "'\n";
}
Question is Updated to understand it clearly.
You already have almost everything you need to get the desired output. You only need to remember the characters that make the input invalid (ie those for which you set isNumber = false;) in a second string and print that instead of the original input. Really the only ingredient that you are not already using in your code is adding a character to a string and that can be done like this:
std::string x;
char invalid_character = 'w';
char other_invalid_character = 'p';
x += invalid_charater;
x += other_invalid_character;
std::cout << x; // prints wp
The Functions I have Implemented is working for a single value but it is still not printing the complete invalid characters.
If the Input is 0123ab456789 so it will print the error message with "a" instead of "ab". It must print "ab" as input contains "ab".
The Code:
#include <iostream>
using namespace std;
int main ( )
{
string i_numvalidation;
cout << "Enter the Number: " << '\n';
cin >> i_numvalidation;
bool isNumber = true;
int bad_index = 0 ;
if (i_numvalidation [0] == '0')
isNumber = false;
for (int i = 0; i < i_numvalidation.length () && isNumber; i++ )
{
if (!(i_numvalidation [i] >= '0' && i_numvalidation [i] <= '9'))
{
isNumber = false;
bad_index = i ;
break;
}
}
if (isNumber)
{
cout << " The Entered " << i_numvalidation << " number is correct" << '\n';
}
else
cout << " The Entered " << i_numvalidation << " is not allowed or Contains invalid input such as '" << i_numvalidation [ bad_index ] << "'\n";
}
Like:
String err='1';
for(int i=0;i<i_numvalidation.length(); i++)
{
if(i_numvalidation[i]!= '0' || i_numvalidation[i]!= '1' || i_numvalidation[i]!= '2' and so on...)
{
err[err.length()]=i_numvalidation[i];
isNumber=false;
}
}
if(!isNumber)
cout<<"That's not a number bruh"<<err<<endl;
Sorry if I'm not helpful, I tried...
Hope you'll get the answer.

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;
}

How to Accept [ENTER] key as an invalid input and send out error message

This is a program that grade user inputs for the questions of Driver's License Exam.
I'm having trouble of validating the user input.
I'd like to accept the [ENTER] key as an invalid input and proceed to my validation rather than just go to an empty line and cannot process to the next question. Purpose is to send out error message and that no input is given and [ENTER] key is not valid input and only accept one more chance to enter valid input which are a/A, b/B, c/C, or d/D. So that is why I'm using if statement here instead of loop.
I tried if (testTakerAnswers[ans] == (or =) '\n') {} but still doesn't solve the problem of newline.
I include curses.h in here hope to use getch() statement from the other post but somehow I can't manage to work in my code with an array instead of regular input.
I'm looking for other methods as well rather than getch()
So should I adjust my bool function, or directly validate input in main() function.
#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
#include <curses.h>
using namespace std;
const unsigned SIZE = 20; // Number of qns in the test
char testTakerAnswers[SIZE]; //Array to hold test taker's answers
bool validateInput(char);
class TestGrader
{
private:
char answers[SIZE]; // Holds the correct answers // Answer is array
int getNumWrong (char[]);
void missedQuestions (char[]);
public:
void setKey(string); // Initialize object with standard keys
void grade(char[]); // Grades the answers from tester
};
void TestGrader::setKey(string key){
if (key.length()!=SIZE){
cout << "Error in key data.\n";
return;
}
for (unsigned pos = 0; pos < SIZE ; pos ++)
answers [pos] = key [pos];
}
void TestGrader::grade(char test[])
{
int numWrong = getNumWrong(test);
if (numWrong <= 5)
cout << "Congratulations. You passed the exam.\n";
else
cout << "You did not pass the exam. \n";
cout << "You got " << (SIZE-numWrong) << " questions correct. \n";
if (numWrong > 0){
cout << "You missed the following " << numWrong << " questions: \n";
missedQuestions(test);
}
}
int TestGrader::getNumWrong(char test[])
{
int counter = 0;
for (int i = 0; i < SIZE; i++){
if (answers[i] != toupper(testTakerAnswers[i])){
counter++;
}
}
return counter;
}
void TestGrader::missedQuestions(char test[])
{
// cout << testTakerAnswers[i]; This is to print taker's answers
int counter = 0;
for (int i = 0; i < SIZE; i++){
if (answers[i] != toupper(testTakerAnswers[i])){
cout << "\n" << i + 1 << ". Correct answers: " << answers[i];
counter++;
}
}
}
bool validateInput(char ans){ // Only A, B, C, D valid input
if (toupper(ans)!='A' && toupper(ans)!= 'B' && toupper(ans)!='C' && toupper(ans)!= 'D'){
cout << "\n********************WARNING*******************\n";
cout << "Invalid input! Enter only a/A, b/B, c/C, or d/D\n";
return false;
}
if (testTakerAnswers[ans] == '\n'){
return false;
}
return true;
}
int main()
{
const int NUM_QUESTIONS = 20;
string name; //Test taker's name
char doAnother; //Control variable for main processing loop
TestGrader DMVexam; //Create a TestGrader object
DMVexam.setKey("BDAACABACDBCDADCCBDA");
do {
cout << "Applicant Name: ";
getline(cin,name);
cout << "Enter answer for " << name << ".\n";
cout << "Use only letters a/A, b/B, c/C, and d/D. \n\n";
for (int i = 0; i < NUM_QUESTIONS; i++){
// Input and validate it
do{
cout << "Q" << i+1 << ": ";
cin >> testTakerAnswers[i];
if (!validateInput(testTakerAnswers[i])){
cout << "You get one more chance to correct.\nOtherwise, it count as wrong answer.";
cout << "\n*********************************************";
cout << "\nRe-enter: ";
cin >> testTakerAnswers[i];
cout << '\n';
break;
}
}while(!validateInput(testTakerAnswers[i]));
}
//Call class function to grade the exam
cout << "Results for " << name << '\n';
DMVexam.grade(testTakerAnswers);
cout << "\nGrade another exam (Y/N)? ";
cin >> doAnother;
while (doAnother != 'Y' && doAnother != 'N' && doAnother != 'y' && doAnother != 'n'){
cout << doAnother << " is not a valid option. Try Again y/Y or n/N" << endl;
cin >> doAnother;}
cout << endl;
cin.ignore();
}while(doAnother != 'N' && doAnother != 'n');
return 0;
}
Your issue is cin >> testTakerAnswers[i]; cin is whitespace delimited, that means that any whitespace (including '\n') will be discarded. So testTakerAnswers[i] can never be '\n'.
I'm not sure exactly what you want to do, but possibly try
getline(cin,input_string);
then
input_string == "A" | input_string == "B" | ...
So if only the enter key is pressed, input_string will become "".

cin a char into an int variable to stop a loop

I would like to read numbers into a static array of fixed size 10, but the user can break the loop by entering character E.
Here's my code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
cin >> myArray[i];
if (myArray[i] != 'E')
{
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
cout << count << endl;
system("PAUSE");
return 0;
}
However, I get the following results while entering E:
Enter upto 10 integers. Enter E to end
Enter num 1:5
5
Enter num 2:45
45
Enter num 3:25
25
Enter num 4:2
2
Enter num 5:E
-858993460
Enter num 6:-858993460
Enter num 7:-858993460
Enter num 8:-858993460
Enter num 9:-858993460
Enter num 10:-858993460
10
Press any key to continue . . .
How can I fix this code in the simplest way?
cin fails for parsing character 'E' to int. The solution would be to read string from user check if it is not "E" (it is a string not a single char so you need to use double quotes) and then try to convert string to int. However, this conversion can throw exception (see below).
Easiest solution:
#include <iostream>
#include <cmath>
#include <string> //for std::stoi function
using namespace std;
int main()
{
int myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
std::string input;
cin >> input;
if (input != "E")
{
try
{
// convert string to int this can throw see link below
myArray[i] = std::stoi(input);
}
catch (const std::exception& e)
{
std::cout << "This is not int" << std::endl;
}
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
cout << count << endl;
system("PAUSE");
return 0;
}
See documentation for std::stoi. It can throw exception so your program will end suddenly (by termination) that is why there is try and catch blocks around it. You will need to handle the case when user puts some garbage values in your string.
Just use:
char myArray[10];
because at the time of taking input console when get character then try to convert char to int which is not possible and store default value in std::cin i.e. 'E' to 0 (default value of int).
Use below code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
char myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
cin >> myArray[i];
if (myArray[i] == 'E')
{
break;
}
else
{
cout << myArray[i] << endl;
count++;
}
}
exitloop:
cout << count << endl;
system("PAUSE");
return 0;
}
Output:
Enter upto 10 integers. Enter E to end
Enter num 1:1
1
Enter num 2:E
1
sh: 1: PAUSE: not found
If you debug this, you will find all your myArray[i] are -858993460 (=0x CCCC CCCC), which is a value for the uninitialized variables in the stack.
When you put a E to an int variable myArray[i]. std::cin will set the state flag badbit to 1.
Then when you run cin >> myArray[i], it will skip it. In other words, do nothing.
Finally, you will get the result as above.
The problem is that attempting to read E as an int fails, and puts the stream in an error state where it stops reading (which you don't notice because it just doesn't do anything after that) and leaves your array elements uninitialized.
The simplest possible way is to break on any failure to read an integer:
for(int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
if (cin >> myArray[i])
{
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
If you want to check for E specifically, you need to read a string first, and then convert that to an int if it's not E.
As a bonus, you need to handle everything that's neither int nor E, which complicates the code a bit.
Something like this:
int count = 0;
string input;
while (cin >> input && count < 10)
{
if (input == "E")
{
break;
}
istringstream is(input);
if (is >> myArray[count])
{
cout << myArray[count] << endl;
count++;
}
else
{
cout << "Please input an integer, or E to exit." << endl;
}
}

Generate Random Letters Depending on User Input

I have to make a simple letter guessing game. So far I've finished almost everything but I'm not sure about what to do when it comes to one task.
So before the game begins it asks the user to input two things:
Enter the amount of different characters: (if 4 is entered for example, the letters chosen would be from A to the 4th letter, A-D only)
and
Enter the pattern length:
The pattern length input is working fine, but I'm having a tough time figuring out how to modify the generate code function to add the amount of different characters.
Any tips?
#include <iostream>
#include <random>
#include <string>
using namespace std;
size_t len;
string str;
void generate_code()
{
str.string::reserve(len);
random_device rd;
mt19937 gen{rd()};
uniform_int_distribution<char> dis{'A', 'Z'};
for (size_t i = 0; i < len; i++)
{
str += dis(gen);
}
}
void guess_checker()
{
string guess{};
size_t trial_count = 0, match_count = 0;
do
{
cout << "Enter your guess: " << endl;
cin >> guess;
if (guess.size() != len)
{
cout << "error: invalid guess" << endl;
}
else
{
match_count = 0;
for (size_t i = 0; i < len; i++)
{
if (guess[i] == str[i])
++match_count;
}
cout << "You guessed " << match_count << " character"
<< (match_count == 1 ? "" : "s") << " correctly." << endl;
}
++trial_count;
}
while (match_count != len);
cout << "You guessed the pattern in " << trial_count << " guess"
<< (trial_count == 1 ? "" : "es") << "." << endl;
}
int main()
{
int amount;
cout << "Enter the amount of different characters: ";
cin >> amount;
cout << "Enter the pattern length: ";
cin >> len;
generate_code();
guess_checker();
return 0;
}
Simply change your generator line to:
uniform_int_distribution<char> dis{'A', 'A' + amount - 1};
I would also recommend adding some validation beforehand, such as:
if (amount < 1 || amount > 26) {
cout << "Bad amount" << endl;
// exit or something
}