Problem using 'if' statment to exclude characters in an array

This is a discussion on Problem using 'if' statment to exclude characters in an array within the C Programming forums, part of the General Programming Boards category; In the folllowing code, I have an array of characters called 'data', and I want to scan through it and ...

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    15

    Problem using 'if' statment to exclude characters in an array

    In the folllowing code, I have an array of characters called 'data', and I want to scan through it and write characters to a file ONLY if they are not a digit or a space. I can't get this to happen; it still writes the digits and spaces to the file. I'm assuming that there's something simple I don't know which is preventing me from succeeding. Any help would be greatly appreciated.

    Code:
    //if statement to ignore numbers and spaces
             if(data[pos - 1] !=  "0" && data[pos - 1] !=  "1" && data[pos - 1] !=  "2" && data[pos - 1] !=  "3" &&
             	data[pos - 1] !=  "4" && data[pos - 1] !=  "5" && data[pos - 1] !=  "6" && data[pos - 1] !=  "7" &&
                data[pos - 1] !=  "8" && data[pos - 1] !=  "9" && data[pos - 1] !=  " ")
             {
             fprintf(coding_seq, "%c", data[pos - 1]);
                
                //if a base was found, move on to the next one
                j++;
             }
    Sorry about the sort of whacky indentation, somehow my formatting was lost when I pasted it

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,434
    isspace()
    isdigit()
    ?

    > Sorry about the sort of whacky indentation, somehow my formatting was lost when I pasted it
    Yeah, that happens when you use an editor which is set to mix spaces and tabs for indentation.
    If you set it to only use spaces all the time, then there is never a problem with any tool / browser / whatever making a complete mess of your beautiful code.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,422
    Quote Originally Posted by Salem View Post
    If you set it to only use spaces all the time, then there is never a problem with any tool / browser / whatever making a complete mess of your beautiful code.
    Yeah, or tabs, depending on what's more convenient, what you like best and what the IDE / editor supports.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    It's much easier if you use the ASCII values to do this (see http://www.cpptutor.com/ascii.htm). I believe your problem is you don't have enough BRACKETS in your if expression -- II and && should usually be between them. Hopefully this illustrates both issues:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main() {
            char string[]="12)besides being W.E.49's 7th photographer";
            int len=strlen(string), i;
            for (i=0; i<len;i++) {
                    if (string[i] == 32) continue; //spaces
                    if ((string[i] > 47) && (string[i] < 58)) continue;  // numbers
                    putchar(string[i]);
            }
    }
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,403
    It's much easier if you use the ASCII values to do this
    However, it is more readable (and portable, though that might not be important) to use isspace() and isdigit(), or compare to a literal space (' ') rather than 32.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    I think you want

    data[pos - 1] != '0' ...

    NOTE: single quote around the digits. Otherwise you are attempting to compare to the address of a null-terminated string.

  7. #7
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Noob is right. But the isdigit() suggesters are even more on the ball.

  8. #8
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    Quote Originally Posted by master5001 View Post
    Noob is right. But the isdigit() suggesters are even more on the ball.
    I dispute that. The poster is learning basic syntax. Knowing the difference between a character constant and a string is fundamental. They won't achieve that by tossing everything out and using a built-in function/macro. The isdigit() suggesters missed the obvious and are already into slicking up the code.

  9. #9
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    I like you already, nonoob. Your syntaxual line of logic is sound. In this case, it would be to the OP's benefit to use isdigit() and isspace() since

    Example:
    Code:
    if((c >= '0' && c <= '9') || (c == ' ') || (c == '\t') || (c == '\n') || (c=='\v')/* The list goes on */)
    
    // Could be reduced down to:
    if(isdigit(c) || isspace(c))
    And my sloppy less readable version is still cleaner an more optimal than his code. You are right, the OP does need to learn. However if you are teaching someone to drive, you can't just say "Bleh, they don't need to park inside the lines at the parking lot. They are not good at backing out just yet." They are still subject to the same laws as the rest of us. Likewise, everyone needs to read your code regardless of how new you are to programming.

  10. #10
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    Now I feel welcome! For a minute there I thought I walked into a flamer forum. Thanks again master5001 for your patience and understanding.

    I certainly agree that isdigit() is the more elegant way of course. However, the OP's problem, as stated, was one of pure syntax (well, a conceptual disconnect with how to represent constants). The logic was already sound though. If shadow1515 learns how to use '0' or any other single character for future endeavours, he will be better equipped.

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Aside from the suggestions made already (which are all good), can I suggest that if you ever NEED to do something like this for whatever reason:
    Code:
             if(data[pos - 1] !=  "0" && data[pos - 1] !=  "1" && data[pos - 1] !=  "2" && data[pos - 1] !=  "3" &&
             	data[pos - 1] !=  "4" && data[pos - 1] !=  "5" && data[pos - 1] !=  "6" && data[pos - 1] !=  "7" &&
                data[pos - 1] !=  "8" && data[pos - 1] !=  "9" && data[pos - 1] !=  " ")
    that you do it this way instead:
    Code:
       char ch = data[pos-1];
       if(ch !=  '0' && ch !=  '1'  && ch !=  '2' && ch !=  '3' ...
    or possibly:
    Code:
    switch (data[pos-1])
    {
        case '0':
        case '1':
        ...
        case '9':
        case ' ':
        // etc. 
            break;
         default:
            fprintf(...);
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Quote Originally Posted by nonoob View Post
    For a minute there I thought I walked into a flamer forum.
    Yeah sometimes it feels like that. If you are new you get flamed for what you don't know, if you are experienced you get everything you say compared to the most recent C/C++ standard all while your every thought is disected and critiqued by all. You just gotta learn no one has any hard feelings. We just try to keep one another honest or kill bordom. Perhaps both. Usually when people like me or matsp critique its just to avoid misconception. Elysia and CornedBee will typically argue the merits of your coding style and use or misuse of the standards. But despite all the opposition we are all actually very nice people who are just killing time. Don't let any of us fool you into thinking otherwise.

    Oh yeah... never underestimate how sleep deprived your typical software engineer can get and the irritability that can ensue.

  13. #13
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by master5001 View Post
    Yeah sometimes it feels like that. If you are new you get flamed for what you don't know, if you are experienced you get everything you say compared to the most recent C/C++ standard all while your every thought is disected and critiqued by all. You just gotta learn no one has any hard feelings. We just try to keep one another honest or kill bordom. Perhaps both. Usually when people like me or matsp critique its just to avoid misconception. Elysia and CornedBee will typically argue the merits of your coding style and use or misuse of the standards. But despite all the opposition we are all actually very nice people who are just killing time. Don't let any of us fool you into thinking otherwise.

    Oh yeah... never underestimate how sleep deprived your typical software engineer can get and the irritability that can ensue.
    Not to mention that most of the more senior members here are anal pedants (and I mean that in the nicest possible sense), so they [me included] will point out any discrepancy between actual facts and what the others have written.

    Computers are finicky and a lot of things depend on getting every detail right. So it's natural that people who are working with detailed software work, will become obsessed with details of the code they look at, even if it may seem petty.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  14. #14
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Which is why I can honestly say I love matsp like family. Not one of the needy relatives who is always asking for money. But like a grandfather who tells interesting stories about the good old days. The good news is, our constant abuse of one another makes us all the more tolerant of non-constructive criticisms. Which is surprisingly a very important asset in the industry. Don't expect all your employers to be more competent than you. And do not expect to always be teamed up with easy going folks who can handle you saying "Dude, your GUI you spent all day on yesterday is absolute crap. I tried clicking 'Ok' and for some reason I got 'Cancel' because they are so close to one another."

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with reading characters
    By csvraju in forum C Programming
    Replies: 4
    Last Post: 03-31-2009, 07:59 AM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM
  5. From stream/file to a string array problem
    By dradsws in forum C Programming
    Replies: 2
    Last Post: 10-01-2001, 06:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21