int countDigits(string word)
{
    int count = 0;
    
    for (int i = 0; i < word.size(); i++)
    {    
        if (word.at(i) < 57 && word.at(i) > 49)
        {
            count++;
        }
    }
}

i want to count the digits in a string "abc123". i know my problem is in the if statemnt i just cant get it working

stupid question i know im just stuck

you can use the macro isdigit() to find out if it is '0' to '9'. And the At() method is unnecessary. if( isdigit(word[i]) )

you can use the macro isdigit() to find out if it is '0' to '9'. And the At() method is unnecessary. if( isdigit(word[i]) )

Is [B]isdigit[/B] a macro then?
According to this information it isn't :P

Change your comparison to if (word[i] < 57 && word[i] > 49) Also, the line is better written as if (word[i] > 49 && word[i] < 57) It's a more logical order for the comparison pair.

Change your comparison to if (word[i] < 57 && word[i] > 49) Also, the line is better written as if (word[i] > 49 && word[i] < 57) It's a more logical order for the comparison pair.

Yes, but isn't the isdigit function a bit easier to work with?
However if he isn't allowed to use that function it would seem more logical to me if he'd written it like you did :)

Member Avatar for jencas

And why 49 and 57 instead of '0' and '9'??? Are you training for an obfuscation contest?

commented: Absolutely right! +9

And why 49 and 57 instead of '0' and '9'??? Are you training for an obfuscation contest?

Agreed, '0' and '9' makes your code more readable, but the OP started with using the ASCII codes :P
But this is actually not a good reason to avoid this I think :)

I would solve it in this efficient easy way

#include <iostream>
#include <string>
using namespace std;

int countdigits(string word)
{
	int count=0;
	for(int i=0;i<(int)word.length();i++)
	{
		if(isdigit(word[i]))
			count=count+1;
	}
	return count;
}
void main()
{
	string word;
	getline(cin,word);
	int digits=0;
	digits=countdigits(word);
	cout<< digits<<endl;
}
commented: IMHO that's the best solution :) +36
commented: Although your algorithm is fine enough, there is no excuse of using void main -2
Member Avatar for jencas

Agreed, '0' and '9' makes your code more readable, but the OP started with using the ASCII codes :P
But this is actually not a good reason to avoid this I think :)

I didn't quote your answer because my answer was intended to address the TO.

Is [B]isdigit[/B] a macro then?
According to this information it isn't :P

Its probably implementation dependent. You have to check your compiler's ctype.h header file to find out whether its implemented as a macro or a function. The link you posted doesn't say one way or the other.

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.