Hi guys, newbie here, some questions!

This is a discussion on Hi guys, newbie here, some questions! within the C Programming forums, part of the General Programming Boards category; Hi there Ok, basically I'm pretty new to C and have created a mashed-together program using different elements from different ...

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

    Hi guys, newbie here, some questions!

    Hi there

    Ok, basically I'm pretty new to C and have created a mashed-together program using different elements from different existing programs:

    Code:
    #include <stdio.h>
    
    #define ALPHABET_TOTAL 26                    /* Defines the total number of letters in the alphabet */
    
    main()
    {
          int text[ALPHABET_TOTAL] = {0},        /* Creates an array of size 26, acting as counters initialized as 0*/    
              text_input,                        /* Reads in the text input as characters */
              ASCII_count,                       /* ASCII number of the letters in the alphabet */
              alpha;                             /* boolean flag which turns to 0 (false) in case of a non-alpha character */
          
    /* Setting values to 0 */
          
          text_input = 0;
          ASCII_count = 0;
          alpha = 0;
    
    
    /* Get input - this needs to change!! */
    
          FILE *userfile; /* declares file pointer */
    
          printf("Enter file name to load: ");
    
          scanf("%s", filename);
     
          userfile = fopen("%s", "r");
    
          
     /* Perform text analysis*/    
    
    
          while( text_input != EOF )
          {
            alpha = 1;
            text_input = getchar();    
            
    /* If input is alphabetical, convert to a number 0-25 so that it can be used as a locator along the array */
          
          if(text_input >= 'a' && text_input <= 'z')
           text_input -= 'a';
          else if(text_input >= 'A' && text_input <= 'Z')
           text_input -= 'A';
    
    /* Non-alphabetical character, set the alpha flag to false */
        
          else
           alpha = 0;
    
    /* Increment the appropriate counter in the text array as long as the character is alphabetical */
        
          if(alpha)
           text[text_input]++;
         }
        
    /* Display results */
        
        for (ASCII_count; ASCII_count <= 25; ASCII_count++)
         printf("\nTotal %c or %c: %d", ASCII_count + 'a', ASCII_count + 'A',text[ASCII_count]);
    }
    As you can probably tell, I'm trying to prompt the user for a file name then conduct a letter frequency analysis on the text contained in said file.
    What's wrong with what I've got? I'm guessing it's the code prompting for the user file.

    Also, If I wanted to add in a counter to keep track of the total number of characters in the text, whereabouts in the various loops would it go?

    Any help would be greatly appreciated. I really want to get to grips with C!

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,033
    OK. First, main should return int, so it should be int main.
    For reading with scanf, see Need help with altering info on a txt file
    The open line is totally wrong. You're trying to open file "&#37;s", which is totally illegal on Windows filesystems, and some others too. But not the one you want to open anyway. You stored that filename into the "filename" variable, so pass that instead.
    Then two suggestions: Indent with more than one space (the ifs) and keep it consitent (that is, indent using the same number of spaces everywher; makes it easier to read). And secondly, indent the comments too.
    And comments can be placed after code, too, not always just on a new line.

    As for your counter, it's very simple. Why not actually read and try to understand the code? If you do, you'll see it becomes very easy.
    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.

  3. #3
    Cogito Ergo Sum
    Join Date
    Mar 2007
    Location
    Sydney, Australia
    Posts
    463
    I think before 'mashing' together anything you need to go over the concepts of basic C.
    It would be good practice to use {} when starting and ending if's and loops.

    Start the main function like so:

    Code:
    int main (void) {
    
    
      return 0;
    }
    Loops

    Code:
    while (i != 10) {
    
      DO SOMETHING
    
      i++;
    }

    Opening files

    Code:
    FILE *fo;
    
    fo = fopen("filename.$", "#"); //# can be a, r or w, or some others, research !!!
                                                   //$ can be only basic text files like rtf or txt
    Copy from one file, writing to another

    Code:
    FILE  *fo;
    FILE  *fw;
    char c;
    
    fo = fopen("C:\\Directory\\Directory\\Directory\\Filename.txt","r");
    fw = fopen("C:\\Directory\\Directory\\Directory\\Output.txt", "w"); 
    
    while(1){
          
          c = fgetc(fo);
          
          if(c == EOF){
            break;
          }
          else{
           PERFORM ACTIONS ON CHARACTERS HERE
            fputc(c,fw);
          }
    }
    Hope some of that helps

  4. #4
    Registered User
    Join Date
    Mar 2008
    Posts
    15
    Cheers guys - I think I do need to try and comprehend the program as a whole more

    Quick question - is it possible to includemore than one 'else if' branch?

    so in this context:

    Code:
      while( text_input != EOF )
          {
            alpha = 1;
            text_input = getchar();    
            
          
          if(text_input >= 'a' && text_input <= 'z')
           text_input -= 'a';
          else if(text_input >= 'A' && text_input <= 'Z')
           text_input -= 'A';
    
          else if(text_input != ' ')
          char_counter++1
        
          else
           alpha = 0;
    
    
        
          if(alpha)
           text[text_input]++;
         }
    ??

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,033
    Quote Originally Posted by fuso View Post
    Quick question - is it possible to includemore than one 'else if' branch?
    As many as you like. Just try to indent a little better.
    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.

  6. #6
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    Code:
    while( text_input != EOF )
          {
            alpha = 1;
            text_input = getchar();
    in this code you firstly process the EOF as regular char, and only then - exit the loop.
    In general - if should be opposit - first thing after input - check the EOF and only if the input is ok - do the rest...
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  7. #7
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    Location
    Seattle
    Posts
    603
    Quote Originally Posted by Elysia View Post
    As many as you like. Just try to indent a little better.
    Just to note, nested if/else code blocks are limited to 15 for c89 and increased to 127 for c99 c coding standard I believe.

    If you happen to have that many try converting those to a switch statement.

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by slingerland3g View Post
    Just to note, nested if/else code blocks are limited to 15 for c89 and increased to 127 for c99 c coding standard I believe.

    If you happen to have that many try converting those to a switch statement.
    Where is this stated? The only limit of 15 is the level of include nesting. There are many other limits that may come into the number nested if-statement, but certainly section 5.2.4.1[which I beleive is the relevant section] doesn't list such a limit.

    --
    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.

  9. #9
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    Location
    Seattle
    Posts
    603
    Quote Originally Posted by matsp View Post
    Where is this stated? The only limit of 15 is the level of include nesting. There are many other limits that may come into the number nested if-statement, but certainly section 5.2.4.1[which I beleive is the relevant section] doesn't list such a limit.

    --
    Mats
    The c99 ISO standard I have reflects

    "[#1] The implementation shall be able to translate and
    execute at least one program that contains at least one
    instance of every one of the following limits:12)

    -- 127 nesting levels of blocks "
    -- 63 nesting levels of conditional inclusion
    :
    :

    You are right about the #include nested statements.

  10. #10
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    63 nesting levels is quite a lot however, and it's a MINIMUM, not a MAXIMUM. So as long as you give the compiler sufficient memory, and it's a modern compiler, it probably copes with a lot more.

    I just wrote a "C code generator" to generate a LONG chain of if/else if statemements, along this concept:
    Code:
    E:\Temp>codegen 3
    #include <stdio.h>
    
    int main()
    {       int x;
            printf("enter a number:");
            scanf("&#37;d", &x);
    
            if (x == 0) printf("x = 0\n");
            else
            if (x == 1) printf("x = 1\n");
            else
            if (x == 2) printf("x = 2\n");
            return 0;
    }
    It compiles and generates correct code in gcc for 3000 if-statements.

    Edit: MS "cl" version 13 fails to compile the same source. It does compile with about 500 if-statements.

    --
    Mats
    Last edited by matsp; 03-12-2008 at 03:40 PM.
    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.

  11. #11
    Registered User
    Join Date
    Mar 2008
    Posts
    15
    Quick question regarding file opening;

    My compiler tells me I have an undefined symbol 'filename' in function main; how (and where) do I define it?

    Code:
         printf("Type a file name, followed by the <enter> key : ");
    
         gets(filename);
    
         fp=fopen(&filename[0],"a+");
    If anyone can help then thanks.

  12. #12
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    I have an undefined symbol 'filename'
    Have you defined filename variable?
    do not use gets - read FAQ
    Code:
    char filename[MAX_PATH];
    if(fgets(filename, sizeof filename,stdin) == NULL)
    {
       /* failed to read a name */
    }
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  13. #13
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Don't use gets(something), use fgets(soemthing, sizeof(something), stdin). That prevents someone leaning on the 'a'-key for 2 minutes and then hitting enter from crashing your program [aka "the Mattias method", which involves putting your entire lower arm straight across the keyboard].

    A good declaration for filename would be
    Code:
    #include <limits.h>    // Should be around your other #include statements.
    ...
      char filename[MAX_PATH];
    ...
    As to where you declare filename[]: it should be declared in the scope where it's needed - so in your case, I suppose at the top of the function main().

    Code:
    fp=fopen(&filename[0],"a+");
    Can be written as:
    Code:
    fp=fopen(filename,"a+");
    And that is what you really should be doing.

    --
    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
    Registered User
    Join Date
    Mar 2008
    Posts
    15
    I think for my purposes, gets() should be fine - the filename will not be longer than 99 characters.

    Do I define 'filename' as a string?

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,033
    Quote Originally Posted by fuso View Post
    I think for my purposes, gets() should be fine - the filename will not be longer than 99 characters.
    No! Never.
    The reason everyone is suggesting fgets (which you should use) is because it is not prone to buffer overruns. Buffer overruns is a security issue, meaning that others can take control of your (!) and others (!!) computer, or even worse stuff.
    So never ever use gets. Always use fgets. Fgets is safe.
    In the Christian mythology, gets is the devil. It should never have been invented. You should stay away from it. Forget it exists. Toss it into the bowels of oblivion and teach all your friends to do the same.

    Do I define 'filename' as a string?
    If it is used to hold text, then yes. That's what strings are for, to hold text, characters and strings.
    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.

Page 1 of 4 1234 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. questions....so many questions about random numbers....
    By face_master in forum C++ Programming
    Replies: 2
    Last Post: 07-30-2009, 09:47 AM
  2. Pipes, inheritence, newbie questions
    By grasshopa in forum Windows Programming
    Replies: 0
    Last Post: 02-28-2006, 06:17 AM
  3. Newbie IO questions
    By gustavosserra in forum C Programming
    Replies: 5
    Last Post: 08-29-2003, 09:09 AM
  4. More newbie questions
    By sunzoner in forum C++ Programming
    Replies: 3
    Last Post: 06-11-2002, 07:23 AM
  5. questions questions questions.....
    By mfc2themax in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 08-14-2001, 08:22 AM

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