isdigit in a simple for loop

Hey
I am trying to create a program that uses isdigit in a for loop to make sure the input is a digit but when i input 12av34 all i get at port b is 12 please help (the writportb is a function that writes x to OUSB)
i need it to display an error message if it isnt a proper digit.
ty

int main(int argc, char *argv[])
{
int x = atoi(argv[1]);
for (int x=0; isdigit(x); );
{

WritePortB(x);
return 0;
}



return 0;
}
Last edited on
You have a return statement inside the for loop, so the loop only executes once.
even when i take it out i am getting nothing out for example i am not getting an error message when i enter something liek 3ad4

int main(int argc, char *argv[])
{
int x = atoi(argv[1]);
for (int x = 0; isdigit(x); x)
{
cout << x << endl;
WritePortB(x);

}


return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cctype>
using namespace std;

void WritePortB( char d );


int main( int argc, char *argv[] )
{
   char *c = argv[1];
   while ( *c )
   {
      if ( isdigit( *c ) )
      {
         WritePortB( *c );
      }
      else
      {
         cout << *c << " is not a digit!" << endl;
      }
      c++;
   }
}


void WritePortB( char d )
{
   cout << "Written " << d << " to port B" << endl;
}


a.exe 1234AB567
Written 1 to port B
Written 2 to port B
Written 3 to port B
Written 4 to port B
A is not a digit!
B is not a digit!
Written 5 to port B
Written 6 to port B
Written 7 to port B
Last edited on
Thanks for answering but i need it to be a for loop so i can use a nested if loop to check for ASCII characters in another part of my project
It is in a loop! A 'while' loop!

You can nest any sort of loops. Not that I can see any reason for a separate loop for an ASCII character check: it's just another set of 'if' statements within the while loop.
Last edited on
Yeah i do know that but i am required to have a "for" loop to find if it is a digit i have tried this but it aint working
int main(int argc, char *argv[])
{
char *c = argv[1];
for (int *c = 0 ; isdigit(*c); *c);
{
cout << *c << endl;
}


return 0;
}
This do you? The previous one is simpler.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;

void WritePortB( char d );


int main( int argc, char *argv[] )
{
   for ( unsigned int i = 0; i < strlen( argv[1] ); i++ )
   {
      char c = argv[1][i];
      if ( isdigit( c ) )
      {
         WritePortB( c );
      }
      else
      {
         cout << c << " is not a digit!" << endl;
      }
   }
}


void WritePortB( char d )
{
   cout << "Written " << d << " to port B" << endl;
}


a.exe 1234AB567
Written 1 to port B
Written 2 to port B
Written 3 to port B
Written 4 to port B
A is not a digit!
B is not a digit!
Written 5 to port B
Written 6 to port B
Written 7 to port B
Last edited on
Topic archived. No new replies allowed.