Thread: String Validation

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    37

    String Validation

    Can anybody give me a simple example of a string validation whereby I would validate a string of chars. I checked through the Faqs but it was a little bit over my head.
    Nb: I am comfortable with fgets, sscanf, etc. With typedef, enum, and static, well, I'm still getting there.
    Your help would be very much appreciated.

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    What do you mean by validate? Would strcmp meet your needs? If you're interested in working with strings have a look at http://www.infosys.utas.edu.au/info/...C/CStdLib.html and browse through string.h. strtok is another one you might be interested in using. You specify a "delimiting" character, and when used in a loop, it will separate out all the "substrings" spearated by that character. It's operation is a tad complicated, so make sure you understand what it does to the string before you use it. If you need help PM me and I'll explain how it works.

  3. #3
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Here's an example:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>       // imports isalpha(), isdigit(), etc...
    
    // String validation; In the form of:
    // [alpha][number][alpha] aka: a3e r2q
    int main( void )
    {
      // Input string
    
      char sz[4];
    
      // Get input
    
      fgets( sz, sizeof( sz ), stdin );
    
      // Output input
    
      printf( "You entered: %s\n", sz );
    
      // Validate input
    
      if( isalpha( sz[0] ) && isdigit( sz[1] ) && isalpha( sz[2] ) )
        puts( "Good form" );
      else
        puts( "Bad form, bad!" );
    
      // Successfully exit
    
      return 0;
    }

  4. #4
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    If you need help PM me and I'll explain how it works.
    sean - hey you and a couple of others have been saying this quite a bit on various posts. Doesn't it help the greater good to have this discussion on the thread vice existing in PMs? Just asking a question.

    -Andy
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

  5. #5
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    Good point, but who knows if I'll ever look at this thread again?

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    37
    Thanks alot guys. The best solution I've seen so far is from Kleid-0. strtok() would not be very useful bcos there would be too many characters to delimit. My intention is to validate that an array is composed of alphas only.

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    37
    Hey Andy. I'm a bit new here, still trying to navigate my way around. I have no idea of how to send PMs in this forum yet

  8. #8
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    Click on User CP in the top-left-hand corner.

  9. #9
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by duvernais28
    My intention is to validate that an array is composed of alphas only.
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    int alpha_only ( const char *s )
    {
       if ( !*s )
       {
          return 0;
       }
       for ( ; *s; ++s )
       {
          if ( !isalpha ( *s ) )
          {
             return 0;
          }
       }
       return 1;
    }
    
    int main ( void )
    {
       const char *text[] = 
       {
          "AlphasOnly",
          "abc123",
          "",
          "123abc",
          "1a2b3c",
          "Hello world",
       };
       size_t i;
       for ( i = 0; i < sizeof text / sizeof *text; ++i )
       {
          printf("\"%s\" : %s\n", text [ i ], 
                 alpha_only ( text [ i ] ) ? "yes" : "no" );
       }
       return 0;
    }
    
    /* my output
    "AlphasOnly" : yes
    "abc123" : no
    "" : no
    "123abc" : no
    "1a2b3c" : no
    "Hello world" : no
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  10. #10
    Registered User
    Join Date
    Jan 2005
    Posts
    37
    Good job Dave. Thanks alot.

  11. #11
    Registered User
    Join Date
    Jan 2005
    Posts
    37
    Dave, I tried your example and it works fine. However, I'm having alot of trouble adopting this to a string that is inputed by the user. Actually, all my attempts to adapt it have ended with the program crashing. I would appreciate it if anyone could help me out with this one.

  12. #12
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    Well, show your latest attempt and I will be glad to help.
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

  13. #13
    Registered User
    Join Date
    Jan 2005
    Posts
    37
    Well, bro. I know you won't believe me on this one but the truth is I scrapped it. I can tell you what my results were though. After removing the string data in the text array and initializing it at BUFZIZ. I used fgets to input a string and then attempted to printf the same string making use of the alpha_only function. The program crashed as son as it compiled. I also attempted to initialise the text array as a normal char. It still crashed on compiling. I use boland c++ builderX so on compiling the program runs imediately.

    You may still not believe that I've tried anything but the truth is that I scrapped it. I honestly would not come here and ask questions without working on what I've been given.

  14. #14
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    Alright, I'll give you the benefit of the doubt. Here is how I percieved the answer:

    Code:
    #include <stdio.h>
    #include <ctype.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    void getLine(char**);
    int validate(char*);
    
    int main ( void )
    {
       char* text = NULL; 
       
       printf("Enter a string: ");
       getLine(&text);
    
       printf("%s - %s \n", text, validate(text) ? "yes" : "no");
    
       return 0;
    }
    void getLine(char** message) {
    
        int ch, len = 0;
    
        while((ch = getchar()) != '\n') { //check for end of line
            *message = (char*)realloc(*message, len+1); //increase inputString by 1 char
            if(*message == NULL) {
                puts("Error allocating memory");
                exit(1);
            }
            (*message)[len++] = ch;
        }
        (*message)[len] = '\0'; //add end token
    }
    int validate(char* s) {
    
        for(int i =0; i < strlen(s); i++) {
    
            if(!isalpha(s[i])) 
                return 0;
        }
    
        return 1;
    }
    If you have any questions let me know.
    Last edited by andyhunter; 01-30-2005 at 08:12 PM.
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

  15. #15
    Registered User
    Join Date
    Jan 2005
    Posts
    37
    Thanks alot Andy. Your solution works fine apart from 'i' needing to be declared
    before/outside the for() condition. However, I suspect that I may need to slow down here. I'm working on this project and I have gone way beyond my the study guide I was given so far. I have been able to validate all other fields in my project so far and I have only one week to complete it. I see no way for me to properly learn pointers, memory allocations, and any other data types in such a short time and complete this project(with documentation) in one week. And there will be no point in using what I don't understand.

    I'll definitely be looking into the solutions that I've seen here but at a slower pace. I know that I've already passed this course.

    Thanks alot to all you guys who helped me out

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  2. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  3. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM