c - How to loop through a users input using getchar() and check to see if the characters are an alphabet or a digit -


im totally new programming, picked c manual learn on own. dont want use array im trying practice getchar(). want able output error message if user enters other digit or alphabet. trying practice c library function isalpha() , isdigit(). wrote far, output not quite right.

input 1: "hello"

expected output : "valid output"

input 2: "hello5"

expected output : "valid output"

input 3: "hello!"

expected output : "invalid output"

but program returns "valid input" 3 inputs above please newbie try learn. appreciate it.

#include <stdio.h> #include <ctype.h>  int main () {     char ch;     int len;     int valid;       printf("enter word: ");      for(length = 0; (ch = getchar()) != '\n'; len++)     {          if(isalpha(ch) || isdigit(ch))         {             valid = 1;                   }         else         {             valid = 0;         }      }     printf("input length: %d\n", len);      if (valid == 1)     {         printf("valid\n");     }     if(valid == 0)     {         printf("\n");     }      return 0;    } 

you there. few pitfalls:

1st there typo variable name “length” instead of “len”.

2nd mitchel0022 stated, program display “valid” providing last character entered valid because reassign new value variable ‘valid’ on each iteration. don’t have use ‘break statement since need loop continue in order length, stick flag.

now program should run fine. copy , paste code below:

#include <stdio.h> #include <ctype.h>  int main () {     char ch;     int len;     //flag set true     int valid = 1;      printf("enter word: \n");      for(len = 0; (ch = getchar()) != '\n'; len++)     {         //change flag if character not number nor letter         if(!isalpha(ch) && !isdigit(ch))         {             valid = 0;         }     }     printf("input length: %d\n", len);      if (valid == 1)     {         printf("valid\n");     }     else     {         printf("invalid\n");     }      return 0;    } 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -