I'm writing a program that will take an 8 digit number as input by the user and will evaluate it so if any digit that appears more than 3 times will be labelled as "unacceptable"; if all digits appear 3 or fewer times it is labelled as "acceptable".
So these numbers:
41124535, 13134113, 24255411
would all be labelled as acceptable, but these ones
34233332, 31111412, 55551122
would be labelled as unacceptable.
My approach is if... else chains and nests. So far I've managed to make a chain work, but it can only compare the digits when they repeat up to 2 times. Then I have a nest, but it only works if I write the else part every step of the way, instead of just leaving one single else at the end. This is crucial since the else part in the end will take the algorithm to a new if else nest that will evaluate the rest of the 8 digit long number.
The beginning of the program:
cout << "\n\n\t Input 1st digit:";
cin >> A;
cout << "\t Input 2nd digit:";
cin >> B;
cout << "\t Input 3rd digit:";
cin >> C;
cout << "\t Input 4th digit:";
cin >> D;
cout << "\t Input 5th digit:";
cin >> E;
cout << "\t Input 6th digit:";
cin >> F;
cout << "\t Input 7th digit:";
cin >> G;
cout << "\t Input 8th digit:";
cin >> H;
cout << "\n\t The number is: [";
cout << A;
cout << B;
cout << C;
cout << D;
cout << E;
cout << F;
cout << G;
cout << H;
cout << "]";
the if...else chain:
if (A==B)
cout << " Unacceptable!";
else
if (B==C)
cout << " Unacceptable!";
else
if (C==D)
cout << " Unacceptable!";
else
if (D==E)
cout << " Unacceptable!";
else
if (E==F)
cout << " Unacceptable!";
else
if (F==G)
cout << " Unacceptable!";
else
if (G==H)
cout << " Unacceptable!";
else
cout << " Acceptable";
then the nest with several else commands:
if (A==B)
{
if (A==C)
{
if (A==D)
cout << " Unacceptable!";
else
cout << " Acceptable";
}
else
cout << " Acceptable";
}
else
cout << " Acceptable";
so my guess is an if...else chain with if...else nests for each variable, but I can't work it out.
I'm not sure if you are using nested if statements for a specific reason - challenge, etc.? I'll assume you're not.
You can read the digits as one string - you could read as an int, but then you have to extract the digits from that anyways.
std::string input;
std::cin >> input;
/* validate input, make sure that it's 8 digits,
* that they are all digits, etc. - hint: int isdigit(int c)
*/
You can use a std::map to keep a histogram of the digits.
std::map< char, int > digit_histogram;
for (auto ch : input)
digit_histogram[ch]++;
Then the count of any digit dig is available as digit_histogram[dig]. You can loop through the map, or loop from 0-9 and discard any that is > 3.
This works for any number of digits, and it's 5 lines long without error checking. The point of programming is to make the computer do the work for you ;)
Start with some tests. This helps you understand your requirements, and clarifies your interface and how the function will be called. As this isn't a tutorial on unit testing, I'll just write a simple program that checks all the test cases succeed:
#include <cstdlib>
int main()
{
// these should all return true
if (!validate("41124535")) return EXIT_FAILURE;
if (!validate("13134113")) return EXIT_FAILURE;
if (!validate("24255411")) return EXIT_FAILURE;
// these should all return false
if (validate("34233332")) return EXIT_FAILURE;
if (validate("31111412")) return EXIT_FAILURE;
if (validate("55551122")) return EXIT_FAILURE;
return EXIT_SUCCESS;
}
Obviously this won't compile, as you haven't declared validate(). So let's add it, before main():
#include <string>
bool validate(const std::string& s)
{
return true;
}
It now compiles, but of course it fails because it never returns false. Now we can code the solution. We can count the occurrences of each character with a std::map:
#include <map>
#include <string>
static const int max_repeats = 3;
bool validate(const std::string& s)
{
std::map<char,int> counts;
for (char c: s)
if (++counts[c] > max_repeats)
return false;
return true;
}
Now, this runs, but it fails on the second test (found by commenting out this test and observing a pass - a real unit-test framework would identify the failing test for you).
The failing test has four 1s in it, so it fails. Why was it suppose to succeed? Ah, perhaps we've misinterpreted the requirement! Perhaps it's intended that the string have no more than three consecutive identical characters? Well we can do that too, by keeping count of the most recently seen character and how many repeats.
#include <string>
static const int max_repeats = 3;
bool validate(const std::string& s)
{
char last_seen = 0;
int repeats = 0;
for (char c: s) {
if (c != last_seen) {
// reset the matcher
last_seen = c;
repeats = 1;
} else {
// have we seen too many?
if (++repeats > max_repeats)
return false;
}
}
return true;
}
There are a few things to clean up, such as test cases with exactly three consecutive identical characters, and (perhaps) you might want to validate the length of the argument string.
And you can then convert it into a full program:
#include <iostream>
int main(int argc, char **argv)
{
while (*++argv)
std::cout << *argv << (validate(*argv) ? " OK" : " FAIL") << std::endl;
}
Related
Consider the following code:
#include <iostream>
using namespace std;
int main(){
int a,b;
cout << "Enter two positive numbers:" <<endl;
cin >> a >> b;
if (a<b) cout <<a<<" is less than "<< b<<endl;
else if (a>b) cout <<a<<" is greater than " <<b<<endl;
}
How can I make the program endlessly repeat asking for a new set of numbers as input?
Here's the simplest way of doing what you want (there are other ways). Basically, you just need to 'wrap' the code that you want to repeat in a loop, where the 'test' condition for the loop will always evaluate to true.
Note the comments with "///" I've given:
#include <iostream>
//using namespace std; /// Search this site for "Why using namespace std is bad"
using std::cout;/// Just declare usage of those feature you ACTUALLY use...
using std::cin;
using std::endl;
int main() {
int a, b;
while (true) { /// The test condition will always be "TRUE" so the loop will never end!
cout << "Enter two positive numbers:" << endl;
cin >> a >> b;
if (a < b) cout << a << " is less than " << b << endl;
else if (a > b) cout << a << " is greater than " << b << endl;
// cout /// This line is wrong!
}
}
Feel free to ask for further clarification and/or explanation.
Depends on what exactly do you want your program to do. If you want it to "deny access". For example lets say you have want a number K > 3 always for the program to continue. The all you have to do is use a do- while loop:
do
{
cout << "Enter the value for the sequence: ";
cin >> K;
if ( K <= 3)
{
cout << "Write a bigger number!" << endl;
}
} while(K <= 3);
Otherwise just use a normal loop with the condition suitable for the task.
Suppose your program is to find the Factorial of number and you want it to loop such that it ask for new value from the user
int main()
{
int n;
while (true) {
int factorial = 1;
cin >> n;
if (n==0) {
cout << 0;
}
else {
for (int i=n;i>0;i--) {
factorial = factorial*i;
}
cout << factorial;
}
}
return 0;
}
I'm trying to check two separate inputs if they are integers or not. I'm able to error check one input but I'm not quite sure how to check two separate ones if I'm using the 'get' function and both inputs are from the 'cin' stream. Using c++.
My code for checking one integer is displayed below.
#include <iostream>
using namespace std;
int main() {
int input;
cout << "Enter an integer: ";
cin >> input;
char next;
int x=0;
int done = 0;
while (!done){
next = cin.get();
if (next == ' ' || next == '\n'){
cout << "The Integer that you have entered is: " << input << "\n";
done = 1;
}
else if (next == '.'){
cerr << "Error: Invalid Input. Not an Integer." << "\n";
done = 1;
}
else{
cerr << "Error: Invalid Input. Not a number." << "\n";
done = 1;
}
}
return 0;
}
Well you could use >> into an int all the way through, drop all that get() stuff and character handling, and check cin.fail(). For example (I'll leave working this into your program and repeating it in a loop as an exercise for you):
int x;
cin >> x;
if (cin.fail())
cout << "Not a valid integer." << endl;
You can handle all subsequent input in exactly the same way. There's no reason to only limit operator >> to the first input.
I am trying to write a part of a large code where a string of 2 numbers is inputted by the user and each number is parsed from the string to do simple addition (just wanted to test the parsing for now).
I do the parsing using stringstream which seems to work but using this code to compute multiple cases is not working. Please see code and output below;
#include <iostream>
#include <sstream>
int main()
{
int t;
std::cout << "Enter the number of test cases: ";
std::cin >> t;
std::cout << std::endl;
if (t > 10 || t < 1)
{
std::cout << "Invalid number of test cases!" << std::endl;
return 0;
}
else
{
for (int x = 0; x < t; x++)
{
std::stringstream numbers;
int num_1;
int num_2;
std::cout << "Enter the two numbers (separated by a space): " << std::endl;
std::string input;
getline (std::cin, input);
numbers << input;
numbers >> num_1 >> num_2;
std::cout << num_1 << std::endl;
std::cout << num_2 << std::endl;
std::cout << num_1 + num_2 << std::endl;
}
}
return 0;
}
Code Output
CODE OUTPUT
Enter the two numbers (separated by a space):
0
-13120
-13120
Enter the two numbers (separated by a space):
1 3
1
3
4
Enter the two numbers (separated by a space):
4 5
4
5
9
Enter the two numbers (separated by a space):
6 7
6
7
13
Why is the first case not taking inputs?
Change code early in main to this:
std::cout << "Enter the number of test cases: ";
std::cin >> t; std::cin.ignore();
When you cin>>t, it reads in the number you give it and then stops. Your next input is a getline, which reads to the next end of line...which is the one you typed after the number of test cases. So you're using an empty line for your first input.
cin.ignore() tells it to skip that empty line and go on to whatever you type next.
First, using a value from cin without checking the stream state is almost as bad as using an uninitialized value. Take advantage of the streams explicit bool operator. Second, you are over complicating the code, why would you read in a string of numbers, only too parse them as numbers?
You can simply do this: with an arbitrary number of objects:
cin >> arg1 >> arg2 >> arg3 >> ...
I've modifed your code with these issues in mind:
#include <iostream>
#include <sstream>
int main()
{
int t;
std::cout << "Enter the number of test cases:\n";
if (std::cin >> t) { // succeeded in getting an int
if (t > 10 || t < 1) { // failed in getting a valid number of test cases
std::cout << "Invalid number of test cases!" << std::endl;
return 1; // return value of 0 is reserved for a successful run, returning zero after an error doesn't make sense
}
else { // succeeded in getting a valid number of test cases
for (int x = 0; x < t; x++) {
int num_1;
int num_2;
std::cout << "Enter the two numbers (separated by a space): " << std::endl;
// why use a stringstream here when you can get the same affect by just retrieving
// two integers from cin
if (std::cin >> num_1 >> num_2) { // again always check for valid input
std::cout << num_1 << std::endl;
std::cout << num_2 << std::endl;
std::cout << num_1 + num_2 << std::endl;
}
else { // failed in getting two int's
//...
// handle error
}
}
}
}
else {
//...
// handle error
}
return 0;
}
I'm trying to create a command menu where the user will be able to perform as many commands as he/she wants until pressing "q" which will end the loop. I think I have everything I need to do this except I realized mid-way that my professor asked to use string. When I included string into the program, I began to get error messages saying "could not convert string to bool" wherever there was a while or if statement. What can I do to fix this problem and get my program working. Thanks in advance.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char option;
char number=0;
string s;
string n;
string p;
string q;
char number2;
cout << " Please enter a number: "<< endl;
cin >> number;
do {
cout << " Please enter a command: " << endl;
cout << " s- square the number " << endl;
cout << " n- add the number and (number +1) " << endl;
cout << " p- add the number and (number -1) " << endl;
cout << " q- quit" << endl;
cin >> option;
if (option=s) {
s= number*number;
cout << "Square of this number is : " << s;
}
else if ( option=n){
number2= number+1;
n= number+number2;
cout << "Sum of" << number << "+" << number2 << "is: " << n;
}
else if (option=p) {
number2= number-1;
p= number+number2;
cout << "Sum of" << number << "+" << number2 << "is" << p;
}
else if (option=q)
cout << "Terminating Program";
} while(option);
return 0;
}
you're assigning in the if and else if rather than comparing.
if (option=s) {
should be
if (option=='s') {
note the double =
Also, you need to put single quotes (') around the character choice.
It's a common mistake that even experienced developers make.
These declarations
char number=0;
string s;
string n;
string p;
string q;
char number2;
should all be int
int number=0;
int s;
int n;
int p;
int q;
int number2;
Let me answer as if I were who will evaluate your homework. You have several issues here:
You are asked to use string. Avoid the use of char and string together.
char option; // professor asked to use string: (-1) point
string option; // ok
When you use a single =, like in option="a", you are assigning the value "a" to the variable option. But in the if-else statements you want to compare, so you should use the == comparison operator. Also, you can't compare a char with a string.
if(option = "a") // error: expression must have bool type: (-2) points
if(option == 'a') // error: no operator "==" matches std::string == char; (-2) points
if(option == "a") // ok
You use while(option), but option is declared as a char, not as a bool. Replace this line to while(option!="q") to finish when you enter q.
while(option); // error: expression must have bool type; (-2) points
while(option != "q"); // GOOD!
Also, your program will finish when you scape from the while-statement; so, try to put the "Terminating Program" message after this.
You do not need to declare such many variables (s, n, p, q, number2). Try to use temporary variables inside each scope, for example:
if (option=="s")
{
cout << "Square of this number is : " << number*number << endl;
}
else if ( option=="n")
{
int number2= number+1;
cout << "Sum of " << number << "+" << number2 << " is : " << number+number2 << endl;
}
In the form you write this code, every time you type a new option you will obtain an output like:
Sum of 10+11 is : 21 Please enter a command:
This is ugly to me (-1 point). Try to put a newline (<< endl;) after every cout lines.
Finally, what if I type any other letter not listed in the menu? I would expect a message like Enter a valid option (-1 point).
I have made a "program" that just says welcome! Type two numbers you want to be added to each other:
there you type the two numbers and then you get the answer out...
When that is done it says: Press any key to continue . . .
When you press a key the program shuts down, but I want it to restart when you pres any key...
How do I do that? I use Microsoft visual studio express 2013 for windows desktop...
langue is C++
This is my code:
#include <iostream>
#include <limits>
#include <cstdio>
using namespace std;
int Add(int x, int y)
{
cout << "Calculating the sum of " << x << " + " << y << "\n";
return (x + y);
}
int main()
{
cout << " Welcome!\n";
int a, b, c;
cout << "Type two numbers you want to be added to each other: ";
cin >> a;
cin >> b;
c = Add(a, b);
cout << "The answere is: " << c;
cout << "\nShutting down....\n\n";
system("pause");
return 0;
}
To loop, you can use while.
For example:
while (false) {
std::cout << "You will never see this output" << std::endl;
}
bool loop = true;
while (loop) {
std::cout << "Type 'quit' to quit this loop." << std::endl;
std::string input;
// This will grab a *single word* from the input. If you want a line, look
// at std::getline
std::cin >> input;
if (input == "quit") {
loop = false;
}
}
while (true) {
std::cout << "This will be repeated forever" << std::endl;
}
There are also two other forms, do while:
std::string input;
do {
std::cout << "Type 'quit' to quit." << std::endl;
std::cin >> input;
} while (input != "quit");
... and for (which is generally used for loop over a defined list of things):
for (size_t i = 0; i < 10; ++i) {
std::cout << i << " out of 10" << std::endl;
}
Technically you can use any of these loop types for any kind of looping, but I suspect the type you want is either one of the two standard infinite loops (whichever one you prefer):
while (true) {
// stuff to repeat forever
}
for (;;) {
// stuff to repeat forever
}
... or a do while loop similar to the do { ... } while (input != "quit"); loop above.
int main()
{
cout << " Welcome!\n";
int a, b, c;
while (true)
{
cout << "Type two numbers you want to be added to each other: ";
cin >> a;
cin >> b;
c = Add(a, b);
cout << "The answere is: " << c;
cout << "\nPress a key to go again....\n\n";
system("pause");
};
return 0;
}
You can do something like this:
int main()
{
cout << " Welcome!\n";
int a, b, c;
while(true) {
cout << "Type two numbers you want to be added to each other: ";
cin >> a;
cin >> b;
c = Add(a, b);
cout << "The answere is: " << c;
cout << "\nPress any key to continue\n";
system("pause");
}
return 0;
}
Use a do while loop mentioning your condition
before exiting the program so that you can determine when to continue and when to exit
I am not sure I understand your question, but I think this is what you are looking for. Have a boolean that determines if the program will loop or not.
int main() {
// stillRun is true while we want to keep looping the program
boolean stillRun = true;
while(stillRun) {
runProgram() ; // this function has all the other code in your old main() function
cin >> stillRun ;
}
}