: : : : Hi again
: : : :
: : : : I have to implement the following function that returns the number of digit character ('0' to '9') in a string.
: : : :
: : : :
int countDigit(char str[]);[/b]
: : : :
: : : :
: : : : So I wrote the following code using
isdigit.
: : : : I think this is fine but, it doesn't execute pointing out that declaration is missing at
int main(){ part. No idea why...
: : : :
: : : : Would anyone advise?
: : : :
: : : : (**The main function was provided, I just need to create the function
countDigit by using provided function prototype)
: : : :
: : : : Thanks!!
: : : :
: : : :
: : : : #include <stdio.h>
: : : : #include <ctype.h>
: : : :
: : : : int countDigit(char str[]) {
: : : : int i;//For-Loop counter
: : : : int count = 0;//Initialise the counter to zero
: : : :
: : : : //Search through the string str[] to find ho many digits it contains
: : : : for (i=0; str[i] != '\0'; i++) {
: : : : if (isdigit(str[i])) {//If it is a digit in the string str[],
: : : : count++;//increase the count = counter show the number of digit
: : : : } else {//If it's not a digit,
: : : : continue; //Ignore and continue looping to find the next char or digit
: : : : }/*end for*/
: : : :
: : : : return count;
: : : : }/*end countDigit*/
: : : :
: : : : int main() {//Debug found on this line!![/red]
: : : : char str[] = "ABCDEFGHIJKLMNOPQRSTUVQYXZ1234567890";
: : : :
: : : : printf("%d\n", countDigit(str));
: : : :
: : : : fflush(stdin); use rewind(stdin) fflush(stdin) has a undefined behaviour according to the c standard
: : : : getchar();
: : : :
: : : : }/*end main*/
: : : :
: : : :
: : : :
: : : :
: : :
: : :
: :
: : Hi Shaolin
: :
: : I was advised that from this msg board, I think it was you.
: : I don't normally use fflush(stdin) since then but this main function (which includes fflush(stdin) to hold the screen) was provided as the template so I couldn't change. ;)
: :
: : Thanks tho.
: :
: :
: :
:
: No problem, I use to use that same method. rewind(stdin) seems to be a safe bet but I even found someone on the internet who said that wouldn't work either but I find no mention of that in the c standard though. If anyone can or has a better work around I would appreciate to see it.
:
:
:
It is explicitly written in ANSI C that using fflush() on input streams is undefined behaviour. However, the standard doesn't mention any reason why you couldn't use rewind() or fseek() on an input buffer.
But if you do so, you may leave garbage in the OS's internal buffers.
Or so they say at comp.lang.c:
http://c-faq.com/stdio/stdinflush2.html