C: Getting wrong output which might have to do with null terminator? -


i writing program takes input of chars *intext, , shifts each alphabetical character amount shift create output of chars *outtext, (eg. in case of main function shown below, input "the quick brown fox jumps on lazy dog." should output gur dhvpx oebja sbk whzcf bire gur ynml qbt., shifting each letter 13.

the output however, aur ~\202vpx o\177|\204{ s|\205 w\202z}\200 |\203r\177 \201ur yn\207\206 q|t. don't know how null terminators work, think may have reason issue.

#include <stdio.h> #include <string.h> #include <ctype.h>  void confab(const char* intext, int shift, char* outtext) {     // visit each char of intext     // assign current val of intext current val of outtextheck     // if current val of intext letter, shift letter     // go next char of intext     outtext[0] = '\0';     while (*intext) {         *outtext = *intext;         if (isalpha(*intext)) {             *outtext = ((*outtext + shift) + '\0');         }         (intext++);         (outtext++);     }     outtext[strlen(outtext)] = '\0'; }  int main(void) {     char buffer[60] = {0};     char* s = "the quick brown fox jumps on lazy dog.";     confab(s, 13, buffer);     printf("%s\n", buffer); } 

problem in format part.

you must take care of lowercase or uppercase first.

check if statement if character lowercase or uppercase.

if (isalpha(*intext)) {     if (isupper(*outtext)) {         *outtext = (((*outtext - 'a') + shift) % 26 + 'a');     } else {         *outtext = (((*outtext - 'a') + shift) % 26 + 'a');     } } 

lowercase , uppercase values have different values in ascii table 1 after another, meaning letter b after a.

to result, have first subtract base character (either 'a' or 'a') mathematical job , after add again base character.

later, replace strlen null termination with

*outtext = 0; 

full code

#include <stdio.h> #include <string.h> #include <ctype.h>  void confab(const char* intext, int shift, char* outtext) {     // visit each char of intext     // assign current val of intext current val of outtextheck     // if current val of intext letter, shift letter     // go next char of intext     outtext[0] = '\0';     while (*intext) {         *outtext = *intext;         if (isalpha(*intext)) {             char t = isupper(*outtext) ? 'a' : 'a';             int tmp = (((int)*outtext - t) + shift) % 26;             if (tmp < 0) {                 tmp += 26;             }             *outtext = tmp + t;         }         (intext++);         (outtext++);     }     *outtext = 0; }  int main(void) {     char buffer[60] = {0};     char* s = "the quick brown fox jumps on lazy dog.";     confab(s, -1, buffer);     printf("%s\n%s\n", s, buffer); } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -