Thread: Switch is not replacing character as expected

  1. #1
    Registered User
    Join Date
    Aug 2017
    Posts
    13

    Switch is not replacing character as expected

    I'm an old dog trying to teach myself C. I'm using C Primer Plus by Prada and reading the chapter on if, else, else if, switch, continue etc and the problem is asking to take the if else version of this program to be converted into a switch program. The if else program replaces the period and exclamation fine but the way I've written this program seems to just add the exclamations and not replace them. Can someone please clue me in as to where I'm going wrong with this thing? Thank you!



    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    
    const char EXCL = '!';
    
    
    int main(int argc, const char **argv)
    {
        int ch;
        int sub, sub1;
        
        printf("Enter some text. '.' replaced with '!' and '!' replaced with '!!'.\n");
        
        while((ch = getchar()) != '#')
        {
            if(ch == '\n')
                continue;
            
            putchar(ch);
            
            if(ch)
            {
                switch(ch)
                {
                    case '.':
                        putchar(EXCL);
                        sub++;
                        break;
                    
                    case '!':
                        putchar(EXCL);
                        putchar(EXCL);
                        sub1++;
                        break;
                    
                    default:
                        break;
                }                          //switch
            }                              //if
        }                                 //while
        printf("\n%d .'z and %d !'z", sub, sub1);
        
        return 0;
    }
    Last edited by Mad_hatter69; 08-06-2017 at 03:05 PM. Reason: Typo

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    The first putchar(ch) outputs the character as is, before you "replace" it. Presumably you should put that line in the default case instead.

    I don't see the point of if (ch == '\n') continue. Don't you want to output the newlines? Maybe you would rather use the '\n' as the ending character instead of the arbitrary '#'.

    The if (ch) doesn't seem to be necessary. What do you think it's doing?

    I don't see the point of EXCL. A simple '!' is better.

    The "switch", "if", and "while" comments are just clutter. They don't improve readability but decrease it.

    There's no reason to define argc and argv if you aren't using them.

    You need to initialize your counters to 0.

    BTW, you should put the newline AFTER the line you are outputting at the end, not BEFORE it! Even if you also want one before it, you definitely need one after it since the way it is would cause my prompt to appear on the same line as the output, which is annoying.

    And in English we would usually say 's instead of 'z, but perhaps in your first language it's vice versa.
    Last edited by algorism; 08-06-2017 at 03:45 PM.

  3. #3
    Registered User
    Join Date
    Aug 2017
    Posts
    13
    Quote Originally Posted by algorism View Post
    The first putchar(ch) outputs the character as is, before you "replace" it. Presumably you should put that line in the default case instead.

    I don't see the point of if (ch == '\n') continue. Don't you want to output the newlines? Maybe you would rather use the '\n' as the ending character instead of the arbitrary '#'.

    The if (ch) doesn't seem to be necessary. What do you think it's doing?

    I don't see the point of EXCL. A simple '!' is better.

    The "switch", "if", and "while" comments are just clutter. They don't improve readability but decrease it.

    There's no reason to define argc and argv if you aren't using them.

    You need to initialize your counters to 0.

    BTW, you should put the newline AFTER the line you are outputting at the end, not BEFORE it! Even if you also want one before it, you definitely need one after it since the way it is would cause my prompt to appear on the same line as the output, which is annoying.

    And in English we would usually say 's instead of 'z, but perhaps in your first language it's vice versa.
    [quote]
    Ahhh!!! Thank you @algorism. Putting the putchar() in its proper place makes perfect sense now that I see it. Thank you for the other valuable tips as well. The EXCL was used to keep me in practice for using #define or const char substitution. Just some trick the book recommended to remember so I chose to use it here. The comments were for my benefit and forgot to erase. I honestly thought I needed the if(ch) to get the switch to work... Brain fart really! The argc argv was how xcode set it up. I was thinking the if(ch == '\n') continue was needed to take care of the newline character put in the input buffer by hitting enter. It was a hangup on a previous program and a programmer recommended I take care of it like that. Could I have used getchar() to do that as well? As for my English as a first or second language... Maybe I chose to be an English writing non conformist... Maybe I'm hooked on ebonicz... Or is it phonics?! Maybe I chose to use the right side of my brain just for poopz and gigglez! All joking aside thank you for all your help!!!
    [/quote ]

  4. #4
    Registered User
    Join Date
    Aug 2017
    Posts
    13
    Ahhh!!! Thank you, @algorism. I don't know why i ended up putting the putchar() in the beginning. I put it with the else in the if else program so why not here I have know idea. The if(ch == '\n') continue waz there because i thought i needed it to chomp the newline character in the input buffer after hitting enter. i had that problem a few programz ago and a programmer gave me that fix to clear the buffer. I read on here that it's a common problem with us noobs and getchar() is another fix. I see I don't need it here. The commentz at the end bracketz were for me cuz i was losing my place and just forgot to delete them. The argc and argv were there because that's what Xcode had set up. The newline at the beginning of the printf() is for the very same reason you are annoyed with the cursor placement... it was printing on the same line as the putchar(ch) output. I will add one to the end. Now, as to my English as a 1st or 2nd language... maybe i was having fun with 's' soundz... maybe I'm a nonconformist to the English language and like to dot my t'z and cross my eyez... maybe I'm hooked on ebonicz... or iz it phonicz? Maybe i chose to be creative and use the right side of my brain just for poopz and gigglez. All joking aside @algorism... thank you for helping me see my stoopid mistakez and brain fartz! Greatly appreciated!

  5. #5
    Registered User
    Join Date
    Aug 2017
    Posts
    13

    thank you @algorism

    Ahhh!!! Thank you, @algorism. I don't know why i ended up putting the putchar() in the beginning. I put it with the else in the if else program so why not here I have know idea. The if(ch == '\n') continue waz there because i thought i needed it to chomp the newline character in the input buffer after hitting enter. i had that problem a few programz ago and a programmer gave me that fix to clear the buffer. I read on here that it's a common problem with us noobs and getchar() is another fix. I see I don't need it here. The commentz at the end bracketz were for me cuz i was losing my place and just forgot to delete them. The argc and argv were there because that's what Xcode had set up. The newline at the beginning of the printf() is for the very same reason you are annoyed with the cursor placement... it was printing on the same line as the putchar(ch) output. I will add one to the end. Now, as to my English as a 1st or 2nd language... maybe i was having fun with 's' soundz... maybe I'm a nonconformist to the English language and like to dot my t'z and cross my eyez... maybe I'm hooked on ebonicz... or iz it phonicz? Maybe i chose to be creative and use the right side of my brain just for poopz and gigglez. All joking aside @algorism... thank you for helping me see my stoopid mistakez and brain fartz! Greatly appreciated!

  6. #6
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    I was intrigued by the 'z and wondered if there was a language that used it instead of 's since I'm kind of into languages. Anywayz, glad to help!

  7. #7
    Registered User
    Join Date
    Apr 2017
    Location
    Quetzaltenango
    Posts
    82
    Here's my solution:
    Code:
    #include <stdio.h>
    #define SIZE_OF_OUTPUT 255
    int main(void) {
      char ch;
      char output[SIZE_OF_OUTPUT];
      int i = 0;
      int substitutions = 0;
      
      while (i < SIZE_OF_OUTPUT && (ch = getchar()) != '#') {
        switch (ch) {
        case '!':
          output[i++] = '!';
        case '.' :
          output[i++] = '!';
          substitutions++;
          break;
        default:
          output[i++] = ch;
        }
      }  
      printf("%s\n", output);
      printf("%d substitutions\n", substitutions);
    }

  8. #8
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    But the one before didn't have any limits on input or output size.

    Since we're all having fun though, here's another one, even though I prefer the first version.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <stddef.h>
    #include <string.h>
    
    struct repl_detail {
        int dots;
        int exclaims;
    };
    
    void *xmalloc(size_t bytes) {
        void *p = malloc(bytes);
        if (!p) {
            perror("xmalloc");
            exit(EXIT_FAILURE);
        }
        return p;
    }
    
    struct repl_detail repl(const char *input, char **output)
    {
        struct repl_detail count = { 0, 0 };
        char *out = *output;
        
        while (*input) {
            switch (*input) {
                case '.':
                    count.dots++;
                    if (out) {
                        *out++ = '!';
                    }
                break;
                case '!':
                    count.exclaims++;
                    if (out) {
                        *out++ = '!';
                        *out++ = '!';
                    }
                break;
                default:
                    if (out) {
                        *out++ = *input;
                    }
                break;
            }
            input++;
        }
        
        if (out) {
            *out = '\0';
        }
        return count;
    }
    
    int main(void) {
        char input[2048] = ""; // whatever you prefer.
        fgets(input, sizeof input, stdin);
        
        // Sort of like snprintf(), if the output is NULL, then it will count the number of replacements it would make only.
        char *output = NULL;
        struct repl_detail deets;
        deets = repl(input, &output);
        output = xmalloc(strlen(input) + (deets.exclaims * 2) + 1);
        deets = repl(input, &output);
        printf("%s\n%d .'s and %d !'s.\n", output, deets.dots, deets.exclaims);
        
        free(output);
        return EXIT_SUCCESS;    
    }
    I used it on one of the OP's posts

    C:\Users\jk\Desktop>a.exe < foo.txt
    Ahhh!!!!!! Thank you, @algorism! I don't know why i ended up putting the putchar() in the beginning! I put it with the else in the if else program so why not here I have know idea! The if(ch == '\n') continue waz there because i thought i needed it to chomp the newline character in the input buffer after hitting enter! i had that problem a few programz ago and a programmer gave me that fix to clear the buffer! I read on here that it's a common problem with us noobs and getchar() is another fix! I see I don't need it here! The commentz at the end bracketz were for me cuz i was losing my place and just forgot to delete them! The argc and argv were there because that's what Xcode had set up! The newline at the beginning of the printf() is for the very same reason you are annoyed with the cursor placement!!! it was printing on the same line as the putchar(ch) output! I will add one to the end! Now, as to my English as a 1st or 2nd language!!! maybe i was having fun with 's' soundz!!! maybe I'm a nonconformist to the English language and like to dot my t'z and cross my eyez!!! maybe I'm hooked on ebonicz!!! or iz it phonicz? Maybe i chose to be creative and use the right side of my brain just for poopz and gigglez! All joking aside @algorism!!! thank you for helping me see my stoopid mistakez and brain fartz!! Greatly appreciated!!
    30 .'s and 5 !'s.
    Last edited by whiteflags; 08-09-2017 at 03:55 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 03-01-2014, 07:45 AM
  2. Replacing character with the string
    By gammie in forum C Programming
    Replies: 2
    Last Post: 06-20-2011, 03:02 PM
  3. Replacing switch statement with a nested if/else
    By dev123 in forum C Programming
    Replies: 27
    Last Post: 09-06-2010, 12:30 AM
  4. Program crashing when replacing newline character
    By mdekom12 in forum C Programming
    Replies: 2
    Last Post: 05-01-2010, 08:49 PM
  5. Replacing switch statements?
    By xuftugulus in forum C Programming
    Replies: 8
    Last Post: 02-16-2008, 10:29 PM

Tags for this Thread