hey,
um i was wondering if anyone could help me with a program where if the user inputs a number no more than 5 digits and the program tells you how many times the number 2 appears in that number.
i know that the modulus and division have to be used but i dont know how to set that part up
can someone help??
thanxxxx

Dani AI

Generated

The thread already shows the two usual approaches: suggested treating the input as a string, and gave the numeric modulus/divide loop. 's snippet worked toward the last digit but had a syntax error and left count uninitialized. Below is a compact, robust variant that validates up to five digits, tolerates an optional sign, and uses the standard library to count how many '2' characters appear.

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

int main() {
    std::string line;
    std::getline(std::cin, line);

    if (!line.empty() && (line[0] == '+' || line[0] == '-')) line.erase(0,1);

    // trim spaces
    size_t a = 0, b = line.size();
    while (a < b && std::isspace(static_cast<unsigned char>(line[a]))) ++a;
    while (b > a && std::isspace(static_cast<unsigned char>(line[b-1]))) --b;
    std::string s = line.substr(a, b - a);

    if (s.empty() || s.size() > 5) return 1; // invalid length
    for (size_t i = 0; i < s.size(); ++i)
        if (!std::isdigit(static_cast<unsigned char>(s[i]))) return 1; // invalid char

    int count2 = static_cast<int>(std::count(s.begin(), s.end(), '2'));
    std::cout << count2 << '\n';
    return 0;
}

Notes and common pitfalls: initialize counters (the uninitialized count in 's code causes undefined behavior), cast to unsigned char before std::isdigit to avoid UB on signed chars, and decide how to treat leading zeros (they are counted here). If the numeric modulus method from is preferred, remember to take abs() for negatives and initialize the counter to zero; a do/while loop handles the input 0 correctly.

Recommended Answers

All 5 Replies

Post what you've got.

get it from the keyboard as a string instead of an integer, then create a loop to check each digit in the string. You don't need modules, division, shifts, or any other math operations, unless, of course, that is a requirement of the problem.

#include <iostream>
using namespace std;
int main()
{
int num1;
int count;

cout<<" Enter an integer :"<<endl;
cin>>num1;

if(num1%10 )==2)
 count+=1

this gave me the last digit it worked but i duno how to get the rest of the digits ( it cant be more than 5 digits so i have to do it 5 times

Try this bit of code:

// Loop until the number becomes 0
while(num1 != 0)
{
	// Check for a 2
	if((num1 % 10) == 2) count++;
	
	// Chop off the last digit
	num1 /= 10;
}

nevermind got it
THanx all for your help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.