C++ Identify first number - visual-c++

I want to make a program where the user can input many numbers but the program will have to identify if the first four or five numbers is equal to the numbers I've set.
ex.
user inputs 0123456789
then if first 5 is equal to number I've set.
Like if ( 01234 = 02134). But all the numbers can be stored in a variable and be displayed again.
Is it possible? Thank you in advance.

this worked.
kind of.
My code is as follows:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main ()
{
int mnum [11];
int ctr;
for (ctr=0; ctr<=10; ctr++)
{
cout << "Enter your mobile number: ";
cin >> mnum [ctr];
}
cout << "Your mobile number is ";
if (mnum [3] == 1||2 && mnum [4] == 3||1)
{
for (ctr=0; ctr<=10; ctr++)
{
cout << mnum [ctr];
}
}
else
{
cout << "Sorry. Invalid mobile number prefix." << endl;
system ("pause");
return main ();
}
return 0;
}
but i have to enter each number. how to make it entr it in one go and still have the same results?

You can use modulus and integer division together to get the individual digits.
Here's a mocked up example that will get each digit of a number and print it individually (notice the output number is reversed because of how I am getting the digits):
int num = 123456;
while(num > 0) {
std::cout << num % 10 << ' ';
num /= 10;
}
Output:
6 5 4 3 2 1

Related

My code is stuck in an infinite loop in C++

I am trying to use a while loop to calculate the average of 3 inputted grades, but I can not enter the next grade as the loops keep on going without giving me the chance to enter the next grade.
#include<iostream>
using namespace std;
int main()
{
int grade = 0;
int count = 0;
int total = 0;
cout << "Enter grade: ";
cin >> grade;
while (grade != -1)
{
total = total + grade;
count = count + 1;
cout << "Enter next grade: ";
cin >> grade;
}
int(average) = total / 3;
cout << "Average: " << int(average) << endl;
system("pause");
}
I tested your code with integer and it works fine.
If you only take int as input, the best is to put something to check the input type. Use cin.fail() to check if user input anything other than int.
for example:
while(cin.fail()) {
cout << "Error" << endl;
cin.clear();
cin.ignore(256,'\n');
cout << "Please enter grade:"
std::cin >> grade;
}
which I refer from https://www.codegrepper.com/code-examples/cpp/how+to+check+type+of+input+cin+c%2B%2B
and here as well Checking cin input stream produces an integer

Do while loop won't break

I am making a Goldilocks game. If the user chooses the wrong answer it would loop back to the beginning of the program. When I try to choose any option it always loops back to the beginning including the correct answer which is 2. I am still new to c++. I do not understand why it is looping to the beginning if the condition is true when 2 is chosen.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void FirstSet()
{
bool win = false;
string PName;
int choice;
int num1, num2, result;
do
{
system("CLS");
cout << " Please Enter Name \n";
cin >> PName;
cout << PName << " and the Three Bears\n\n ";
cout << PName << " Walks up and sees 3 Doors, 1 Large Door, 1 Medium
Door and 1 Small Door. \n\n\n " << "Which Door do you want to Open?\n "
<< " 1 for The Large Door\n " << " 2 for the Medium Door\n " << " 3
for the small door\n ";
cin >> choice;
if (choice == '1')
{
cout << " The large door is too heavy it will not budge.\n "
<< " Please Try Again\n\n ";
system("pause");
}
else if (choice == '2')
{
win = true;
}
else if (choice == '3') {
cout << " The Door is too small you would get stuck.\n "
<< "Please Try Again\n\n";
}
} while (!win);
}
int main()
{
FirstSet();
system("pause");
return 0;`
The reason none of your comparisons are turning true is because you are reading the input into an int variable. Then you are comparing to ascii character values of 1,2 and 3 which happen to be 49, 50 and 51 respectively. If you modify your if lines to compare directly with integers, it should work:
if (choice == 1)
{
...
}
else if (choice == 2)
{
...
}
else if (choice == 3)
{
...
}
Although, for readability purposes and also to avoid such cases, I recommend using switch case statements in this case.

c++ program replace digits in a given number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How would you be able to replace digits in a given number using basic c++. Example if the number is 23444 and you want to take the old digit 4 and replace is with a new digit 5 to get a new number 23555.
I have some work done below but when I enter the inputs, it ends up giving me an incorrect result.
cout << "Enter the number: " << endl;
cin >> number;
cout << "Enter the old digit: " << endl;
cin >> oldDigit;
cout << "Enter the newDigit: " << endl;
cin >> newDigit;
newDigit=oldDigit;
cout << Newnum << endl;
You can convert int to char* using itoa() and iterate over it to
check does it contain number. If it does, get 4's position and replace
it with 5.
I know you didnt work with strings, but it can be helpful in your case.
Simple code:
#include <string.h>
#include <iostream>
#include <stdlib.h>
int main(){
int numer;
std::cin>>numer;
char* str;
itoa(numer, str, 10);
for(int i = 0; i < strlen(str); i++){
if(str[i] == '4') str[i]='5';
}
}
If I understand you correctly, you don't just want to simply add 111, you want to treat the number as a string, then change elements in the array. Is that correct?
This may get you on the right track:
Convert an int to ASCII character
if you really want to use only int to do this, here is a working example (base on some of your code)
#include <iostream>
using namespace std;
int replaceDig( int num, int oldDigit, int newDigit)
{
if(num==0)return 0;
int digit = num%10;
if(digit==oldDigit)digit = newDigit;
return replaceDig(num/10,oldDigit,newDigit)*10+digit;
}
int main()
{
int num, newnum, oldDigit, newDigit;
cout << "Enter the number: " << endl;
cin >> num;
cout << "Enter the old digit: " << endl;
cin >> oldDigit;
cout << "Enter the newDigit: " << endl;
cin >> newDigit;
newnum = replaceDig(num, oldDigit, newDigit);
cout << newnum << endl;
return newnum; //do you really want to return this?
}
I have come up with a solution . Don't know if it contains bug or not. Please let me know.
int num = 23444 ,new_num = 0;
int mod;
int exponent = 0;
/**
* Now form the new number
*/
while ( num > 0 ) {
mod = num % 10;
num /= 10;
if ( mod == 4 ) // check whether this is the old digit or not
new_num += 5 * pow( 10 , exp); // replace with new digit
else
new_num += mod * pow(10 , exp); // otherwise no change
exp++;
}
num = new_num;
std::cout << num;
I hope this works for you -
std::string s = std::to_string(23444);
std::replace( s.begin(), s.end(), '4', '5');
int num = std::stoi(s);
int replaceDig( int num, int oldDigit, int newDigit) // replacing the old digits in a number with a new digit
{
int position = numDigits(num);
int remainder = num;
int currentDigit;
while (remainder >0)
{
currentDigit=(num/pow(10,position))%10;
if(currentDigit==oldDigit)
{
num = num - oldDigit*pow(10,position);
num = num + newDigit*pow(10,position);
}
remainder = remainder/10;
position--;
}
}
This is the general idea, I guess. I didn't try to compile it though. And of course, this version isn't really optimized and we could find some more efficient ways of doing it. Oh, and it doesn't work with negative numbers, but this should be quite easy to adapt.

cin unintentionally skipping user input

I am trying to write a loop that validates user input, and then repeats if the input is bad. The input must be either a binary number (as a string) or a decimal number (as an int). I have seperate functions to validate this input, but they are not causing any trouble.
The problem arises when I select 1 or 2, and then willingly enter an invalid binary or decimal number. At this point, the do-while loop repeats successfully. The program prints another request for user input to cout, But when it comes time for the user to enter input, the program thinks that there is input in the console before I even enter anything. I believe this is a problem with whitespace/control characters in the buffer, but I am not sure how to fix it. I have tried using std::cin >> std::ws to clear any straggling white space, but no luck.
#include <iostream>
#include <string>
#include <limits>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
using std::cout;
using std::cin;
using std::endl;
using std::numeric_limits;
using std::max;
using std::streamsize;
using std::string;
//int toDecimal;
//true is is binary
bool validateBinary(const string &binaryNumber){
for(int i = 0; i < binaryNumber.length(); i++){
if((binaryNumber[i] != 1) && (binaryNumber[i] != 0)){
return false;
}
}
return true;
}
//true if is decimal
bool validateDecimal(){
return cin;
}
int main() {
int conversionType = 0; //we initialize conversionType to a default value of 0 to ensure the copiler it will always have a value
bool isBinary = false;
bool isDecimal = false;
string binaryNumberInput;
int decimalNumberInput;
do {
if(conversionType == 0){
cout << "Enter 1 to convert binary to decimal," << endl;
cout << "2 to convert decimal to binary, " << endl;
cout << "or 3 to exit the program: ";
std::cin >> std::ws; //to clear any whitespace fron cin
cin >> conversionType; //upon a second iteration, this value is read in before a user input is given
}
if(!cin || (conversionType != 1 && conversionType != 2)){
cout << "Incorrect input." << endl;
cin.clear(); //clear the fail bit
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //used to ignore not-numeric input
}
cout << "You have selected option " << conversionType << "." << endl;
if(conversionType == 1){
cout << "Please enter a binary number: ";
cin >> binaryNumberInput;
isBinary = validateBinary(binaryNumberInput);
if(!isBinary){
cout << "The numbered you entered is not a binary number!" << endl;
conversionType = 0;
}
}
if(conversionType == 2){
cout << "Please enter a decimal number: ";
cin >> decimalNumberInput;
isDecimal = validateDecimal(); //true if succeeded, meaning is a number
if(!isDecimal){
cout << "The numbered you entered is not a decimal number!" << endl;
conversionType = 0;
}
}
}
while((conversionType != 1 && conversionType != 2) || (isBinary == isDecimal));
return 0;
}
Rather than debug your current program you might want to consider using the standard library to simply things
#include <iostream>
#include <string>
#include <bitset>
#include <climits>
#include <limits>
template<typename T>
void get(T& value)
{
while (!(std::cin >> value)) {
std::cout << "Invalid input\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
int main()
{
std::cout << "Enter 1 to convert binary to decimal,\n" <<
"2 to convert decimal to binary\n";
int option;
if (std::cin >> option) {
switch (option) {
case 1: {
std::bitset<CHAR_BIT * sizeof(unsigned long long)> bits;
get(bits);
std::cout << bits.to_ullong() << '\n';
break;
}
case 2: {
unsigned long long i;
get(i);
std::cout << std::bitset<CHAR_BIT * sizeof i>(i) << '\n';
break;
}
}
}
}
If you want this to loop you should be able to add it back in again easily enough.

c++ Sum, Average, Largest, Smallest validation issue

So this program calculates and prints the largest, smallest, average, and sum of the sequence a user enters. My only problem that I have found is that when a symbol is entered, it outputs it is wrong, but still ""adds" it's ascii code to the sum, messing up the results. Also, if someone else a number and letter such as 1361351P, it still reads it. Any help is appreciated.
/** C2.cpp
* Test #2 Problem C2
* Robert Uhde
* This program calculates and prints the largest, smallest, average,
* and sum of a sequence of numbers the user enters.
*/
#include <iostream>
using namespace std;
// Extreme constants to find min/max
const double MAX = 1.7976931348623157e+308;
const double MIN = 2.2250738585072014e-308;
// Create generic variable T for prototype
template <class T>
// Prototype dataSet that with request inputs and calculate sum, average, largest and smallest numbers.
T dataSet(T &sum, T &largest, T &smallest, T avg);
int main(){
// Intro to program
cout << "This program calculates and prints the largest, smallest,"
<< endl << "average, and sum of a sequence of numbers the user enters." << endl << endl;
// defined used variables in longest double format to include as many types as possible with largest range
double avg = 0, sum = 0, max, min;
// Call dataSet which returns avg and return references
avg = dataSet(sum, max, min, avg);
// Output four variables
cout << endl << "The largest of the sequence you entered is: " << max << endl;
cout << "The smallest of the sequence you entered is: " << min << endl;
cout << "The sum of the sequence you entered is: " << sum << endl;
cout << "The average of the sequence you entered is: " << avg << endl;
system("pause");
return 0;
}
// Create generic variable T for dataSet
template <class T>
T dataSet(T &sum, T &max, T &min, T avg){
T num;
min = MAX, max = MIN;
// count number of valid numbers
int count = 0;
// Repeat this loop until ^Z
do{
cout << "Enter a sequence of numbers: (^Z to quit) ";
cin >> num;
// if valid, then increment count by 1, add to sum, find out if it's new max or min
if(cin.good() && (typeid(num) == typeid(int) || typeid(num) == typeid(double))){
count++;
if(num > max)
max = num;
sum += num;
if(num < min)
min = num;
}
// if user enters ^Z break out
else if(cin.eof())
break;
// If there is some sort of type error, print so and clear to request again
else{
cout << "Error. Try Again.\n";
cin.clear();
cin.ignore(80, '\n');
}
}while(true);
// Calculate average and then return
avg = sum / count;
return avg;
}
Your conditioning check needs some more work. I would use more specific condition checkings such as isalpha or isdigit which are part of the since these condition checks below are not good enough
if(cin.good() && (typeid(num) == typeid(int) || typeid(num) == typeid(double)))
Best of luck!

Resources