Thread: Finding a number within a number

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    11

    Finding a number within a number

    hi all,

    i have a file that its a .dat file ok it contains approximately 300 number values, each number value is either a 2 , 3 or 4 digit number like this..

    11 111 1678 1334 1445 1335 1225 72 62 42 54 544 944 9111

    and so on a so forth.

    Now what i need to do is make my C Program able to find a particular number within that file.

    I.e All the numbers that have the 2nd number as 1


    Could anyone provide me with the guidance on how to do this
    Thanks

    JC

  2. #2
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    You could use fgets to read each lines (assuming there are multiple lines?), then use strchr to find the ' ' (space character, which appears to delimit the numbers), then check the character two ahead to see if it's '1'. Repeat until there's no more numbers.

  3. #3
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Since the input sounds like it is tightly formatted, I would recommend using fscanf to read each "number" as text. The %s specifier is whitespace delimited, so it will skip the intervening whitespace. Then checking that the second "digit" is a '1' is trivial.
    Code:
    #include <stdio.h>
    
    int main()
    {
       static const char filename[] = "file.txt";
       FILE *file = fopen(filename, "r");
       if ( file != NULL )
       {
          char text[5];
          while ( fscanf(file, "%4s", text) == 1 )
          {
             if ( text[1] == '1' )
             {
                puts(text);
             }
          }
          fclose(file);
       }
       else
       {
          perror(filename);
       }
       return 0;
    }
    
    /* file.txt
    11 111 1678 1334 1445 1335 1225 72 62 42 54 544 944 9111 9191
    */
    
    /* my output
    11
    111
    9111
    9191
    */
    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.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with this compiler error
    By Evangeline in forum C Programming
    Replies: 7
    Last Post: 04-05-2008, 09:27 AM
  2. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  3. Finding the biggest number?
    By Tarento in forum C Programming
    Replies: 2
    Last Post: 05-17-2006, 09:18 PM
  4. Prime number program problem
    By Guti14 in forum C Programming
    Replies: 11
    Last Post: 08-06-2004, 04:25 AM
  5. Random Number problem in number guessing game...
    By -leech- in forum Windows Programming
    Replies: 8
    Last Post: 01-15-2002, 05:00 PM