Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 21
  1. #1
    New Coder
    Join Date
    Nov 2008
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    what's wrong with this code ??

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <conio.h>
    
    char text[256];
    int m,k,c,men;
    
    /*Encrypt*/
    void cez(char *Text)
    {
        printf("%s\n", "vvedite isxodniy text ");
        gets(Text);
        printf("%s\n", "vvedite klu4 shifrovani9 ");
        scanf("%d", &k);
    
        for(m = 0; m < strlen(text); ++m)
        {
            c = text[m] + k;
            if(c > 256) c -= 256;
            Text[m] = c;
        }    
    }
    
    /*Decrypt*/
    void desh(char *Text)
    {
        printf("%s\n", "vvedite klu4 deshifrovki");
        scanf("%d", &k);
    
        for(m = 0; m < strlen(text); ++m)
        {
            c = Text[m] - k;
            if(c < 256) c+=256;
            Text[m] = c;
        }
    }
    int main()
    {
        cez(text);
        printf("%s\n", text);
        
        desh(text);
        printf("%s\n", text);
    
        _getch();
        return 0;
    }
    i cant understand whats the problem when i put the letter o it doesnt give a know letter for some reason..((
    Last edited by Millenia; 11-22-2008 at 06:31 PM. Reason: Please use code tags! [code] etc

  • #2
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by BISKOT188 View Post
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <conio.h>
    
    char text[256];
    int m,k,c,men;
    
    /*Encrypt*/
    void cez(char *Text)
    {
        printf("%s\n", "vvedite isxodniy text ");
        gets(Text);
        printf("%s\n", "vvedite klu4 shifrovani9 ");
        scanf("%d", &k);
    
        for(m = 0; m < strlen(text); ++m)
        {
            c = text[m] + k;
            if(c > 256) c -= 256;
            Text[m] = c;
        }    
    }
    
    /*Decrypt*/
    void desh(char *Text)
    {
        printf("%s\n", "vvedite klu4 deshifrovki");
        scanf("%d", &k);
    
        for(m = 0; m < strlen(text); ++m)
        {
            c = Text[m] - k;
            if(c < 256) c+=256;
            Text[m] = c;
        }
    }
    int main()
    {
        cez(text);
        printf("%s\n", text);
        
        desh(text);
        printf("%s\n", text);
    
        _getch();
        return 0;
    }
    i cant understand whats the problem when i put the letter o it doesnt give a know letter for some reason..((
    - the code tags are [ code] and [ /code] not < code> and < /code>
    - when you use 'o' or any letter after it will shift outside of printable chars. see ASCII for details.

    regards

  • #3
    New Coder
    Join Date
    Nov 2008
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    ox ok sorry well i also figure this out but i have no idea about the solution how to make that work and now shift in unknown chars any ideas?

  • #4
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by BISKOT188 View Post
    ox ok sorry well i also figure this out but i have no idea about the solution how to make that work and now shift in unknown chars any ideas?
    check the result. There are few solution, search for ischar, isprint, isgraph, isascii, or do numeric tests like:
    Code:
    if(c < 127 && c > 'a')
    I'm sorry this seems to be homework, I can give you some direction but that's all, read the forum rules about that.

    regards

  • #5
    New Coder
    Join Date
    Nov 2008
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    no it is not homework it s just a try to understand c language ..mate i ve done this same code in 3 languages ...if you dont beleive i can show you down but in that i didnt have to owercome with that ascii problem whitch appears to me in c...and i have no idea how to turn this out ...

    this was my first code in pascal..
    Code:
    program shfrovalka;
    uses crt;
      var text:string;
      m,k,c,men:integer;
    procedure cez(var text:string; var k:integer);
      begin
      clrscr;
       writeln('vvedite isxodniy text ');
        write('$~/> ');
        read(text);
       write('vvedite klu4 shifrovani9 ');
        readln(k);
       for m:=1 to length(text) do
        begin
         c:=ord(text[m])+k;
         if c>256 then c:=c-256;
         text[m]:=chr(c);
        end;
    end;
    procedure desh (var text:string);
      begin
       writeln('vvedite kluch deshifrovki' );
       readln(k);
        for m:=1 to length(text) do
         begin
          c:=ord(text[m])-k;
           if c<256 then c:=c+256;
          text[m]:=chr(c);
         end;
      end;
    begin
      repeat
        clrscr;
        writeln('1 - shifrovka ');
        writeln('2 - deshifrovka ');
        writeln('3 - sosto9nie texta ');
        readln(men);
         case men of
          1:cez(text,k);
          2:desh(text); U?
          3:begin
             writeln(text);
             readkey;
            end;
         end;
      until men = 0;
    end.
    this was in c++
    Code:
    #include "stdafx.h"
    
    void encode(char *input, char *output, int start); // шифрование
    void decode(char *input, char *output, int start); // расшифровка
    
    int main(int argc, char* argv[])
    {
      setlocale(LC_ALL, "rus"); // определить кодовую страницу для России
      if (argc!=5) {  // задано недостаточное количество параметров командной строки
        cout << "Образец запуска: ";
        cout << "cezar_ascii.exe   encode/decode offset ";
        cout << "input_file - имя входного файла ";
        cout << "output_file - имя выходного файла ";
        cout << "encode - зашифровать ";
        cout << "decode - расшифровать ";
        cout << "offset - величина смещения алфавита замены ";
        exit(1);
      }
        
      for (unsigned int i=0; i
        if (!isdigit(argv[4][i])) {
          cout << "Величина смещения алфавита должна быть числом ";
          exit(1);
        }
      }
      
      if (toupper(*argv[3])=='E') {  // 3-им параметром в командной строке задано Encode - зашифровываем
        encode(argv[1], argv[2], atoi(argv[4]));
      } else { // иначе расшифровываем
        decode(argv[1], argv[2], atoi(argv[4]));  
      }
    
      return 0;
    }
    
    // шифрование
    void encode(char *input,   // имя входного файла
          char *output,  // имя выходного файла
          int start) {   // величина смещения алфавита
      
      ifstream in(input, ios::in | ios::binary);
      ofstream out(output, ios::out | ios::binary);
      try {
        if (!in) {
          cerr << "Не могу открыть входной файл. ";
          exit(1);
        }
        if (!out) {
          cerr << "Не могу открыть выходной файл. ";
          in.close();
          exit(1);
        }
    
        int ch;  // для хранения считываемого символа
        do {
          ch = in.get();  // считываем из файла очередной символ
          if (!in.eof()) {  // признак конца файла не обрабатываем
            ch += start; // производим сдвиг на заданную величину по таблице кодов ASCII
            if (ch>255) {
              ch -= 255; // сдвиг циклический
            }
            out.put((char) ch);  // записать измененный символ в файл результата
          }
        } while (!in.eof());
      } catch (char *errMess) {  // если ошибка
          cerr << errMess << endl;
          if (in) {
            in.close();
          }
          if (out) {
            out.close();
          }
      }
      // закрыть используемые файлы
      if (in) {
        in.close();
      }
      if (out) {
        out.close();
      }
    }
    
    // расшифровка
    void decode(char *input, char *output, int start) {
      
      ifstream in(input, ios::in | ios::binary);
      ofstream out(output, ios::out | ios::binary);
      try {
        if (!in) {
          cerr << "Не могу открыть входной файл. ";
          exit(1);
        }
        if (!out) {
          cerr << "Не могу открыть выходной файл. ";
          in.close();
          exit(1);
        }
    
        int ch;  // для хранения считываемого символа
        do {
          ch = in.get();
          if (!in.eof()) {  // признак конца файла не обрабатываем
            ch -= start; // производим циклический сдвиг на заданную величину в обратном направлении
            if (ch<0) {
              ch += 255;
            }
            out.put((char) ch);
          }
        } while (!in.eof());
      } catch (char *errMess) {
          cerr << errMess << endl;  // вывести сообщение об ошибке
          if (in) {
            in.close();
          }
          if (out) {
            out.close();
          }
      }
    
    // закрыть рание открытые файлы
      if (in) {
        in.close();
      }
      if (out) {
        out.close();
      }
    }
    this is in java
    Code:
    1.1. Шифр Цезаря
    
    Шифр Цезаря основан на фиксированном смещении по кругу букв алфавита. Буквы сдвигаются по кругу, так что после последней буквы алфавита идет его первая буква. В следующем листинге (на языке java) приводится алгоритм шифрования на основе шифра Цезаря.
    
    Листинг 1. класс CaesarCipher
    
    package ru.festu.u031.asanov.security.ref1;
    
    public class CaesarCipher {
    
        /** Зашифровать строку */
    
        public static String encrypt(String s, int key) {
    
            String result = "";
    
            for(int i = 0; i < s.length(); i++) {
    
                // зашифровать каждый символ в строке
    
                result += encrypt(s.charAt(i), key);
    
            }
    
            return result;
    
        }
    
        /** Зашифровать отдельный символ */
    
        public static char encrypt(char c, int key) {
    
            // преобразовать строчные буквы в прописные
    
            if(c >= 'а' && c <= 'я') c = Character.toUpperCase(c);
    
            // "повертуть" букву
    
            if(c >= 'А' && c <= 'Я') c = rotate(c, key);
    
            return c;
    
        }
    
        /** Расшифровать строку */
    
        public static String decrypt(String s, int key) {
    
            // выполнить шифрование с "обратным" ключем
    
            return encrypt(s, -key);
    
        }
    
        /** Расшифровать отдельный символ */
    
        public static char decrypt(char c, int key) {
    
            if(c < 'А' || c > 'Я') return c;
    
            else return rotate(c, key);
    
        }
    
        /** "Поворот" символа */
    
        private static char rotate(char c, int key) {
    
            int l = 'Я' - 'А';
    
            c += key % l;
    
            if(c < 'А') c += l;
    
            if(c > 'Я') c -= l;
    
            return c;
    
        }
    
    }
    and this is my first try to make it in c but i failed to make it run cause couldnt realy understand what was his problem so i made the one i presented you but still couldnt solve the bug problem...this also has an error i couldnt find thank for your time
    Code:
    #include <stdio.h>
    #include <string.h>
    
    void menu ( void ) {
       printf("Please enter a number: \n"
              "1-Encrypt\n"
              "2-Decrypt\n"
              "3-Exit\n"
              "prompt > ");
       fflush( stdout );
    }
    
    int getchoice ( void ) {
       char buff[BUFSIZ];
       int  choice = 0;
       do {
           menu();
           if ( fgets( buff, sizeof buff, stdin ) != NULL ) {
               /* success reading a line, does it make sense? */
               if ( sscanf( buff, "%d", &choice ) != 1 ) {
                   printf( "Enter a number\n" );
               }
           } else {
               /* user EOF, just exit now */
               choice = 3;
           }
       } while ( choice < 1 || choice > 3 );
       return choice;
    }
    
    void encode ( void ) 
    {
        char buff[BUFSIZ];
        int i = 0;
        int shift_value;
         printf( "Doing encrypt\n" );
        printf("\nPlease enter the text you wish to encrypt: ");
        fgets(buff, sizeof(buff), stdin);
            if ("%s"  > 'Z')
        {
           "%s" -= 'Z' - 'A';
        }
        printf("\nEnter your encryption shift value (anything from +-1 to 25): "); 
       scanf ("%i", &shift_value);
        
        
    
        {    
    while ( buff[i] != '\0' )
         {
       buff[i] = buff[i] + shift_value;
       i++; 
       
         }
        }
    printf("\n Your encrypted text is: %s \n", buff);
    }
    void decode ( void ) 
    {
        char buff[BUFSIZ];
        int i = 0;
        int shift_value;
                   printf( "Doing decrypt\n" );
        printf("\nPlease enter the text you wish to decrypt: ");
        fgets(buff, sizeof(buff), stdin);
        printf("\nEnter your encryption shift value (anything from +-1 to 25): "); 
       scanf ("%i", &shift_value);
    
        {
    while ( buff[i] != '\0' ) 
         {
       buff[i] = buff[i] - shift_value;
       i++;
         }
        }
    printf("\nYour decrypted text is: %s \n", buff);
    }
    int main ( ) {
       int choice;
        while ( (choice=getchoice()) != 3 ) {
           if ( choice == 1 ) {
    
               encode();
           } else
           if ( choice == 2 ) {
               decode();
           }
       }
    
    
       return 0;
    }
    i know that something doesnt seem right here but i still dont know how to change it and make it work this c language is realy a pain in the ***...

    Code:
           if ("%s"  > 'Z')
        {
           "%s" -= 'Z' - 'A';
        }
    Last edited by BISKOT188; 11-23-2008 at 07:59 PM.

  • #6
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by BISKOT188 View Post
    no it is not homework it s just a try to understand c language ..mate i ve done this same code in 3 languages ...if you dont beleive i can show you down but in that i didnt have to owercome with that ascii problem whitch appears to me in c...and i have no idea how to turn this out ...
    posting the code is not a poof but I must believe you, that's fair.

    pascal and c, is mapping almost one to one,
    Code:
           if ("%s"  > 'Z')
        {
           "%s" -= 'Z' - 'A';
        }
    this have no sense and also give error when compile you can remove it.

    this is a link to the ascii table:
    http://www.asciitable.com/

    as you can see not all values are printable. I get the code you posted and I must test it, then I come back with feedback.

    best regards

  • #7
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    you have a problem, your algorithm is wrong:

    http://ru.wikipedia.org/wiki/%D0%A8%...B0%D1%80%D1%8F

    do you need text to use upper and lower case characters or only one type?. In this last case which one?

    regards

  • #8
    New Coder
    Join Date
    Nov 2008
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    well i didnt tell you to believe me i just trying to learn a couple of things
    for the ascii yes i saw that page before cause i searched that well i know that not all of them are prinatable so i have to figure out a loop ..to make is run.. as far as i remember is is from 65 to 90 and 97 to 122 but i dont know how to make that loop inside this chars only ..

    and about the code i gave you my first try it makes if you think it a bit different and see all the code anyway ....

    there is an error c2016 if i remember well but i tried to do like this

    instead of that 2 lines

    [code]

    int x;
    if (x > 'Z')
    x -= 'Z' - 'A';

    printf("\n Your encrypted text is: %x \n", buff);
    [\code]

    well in that way i could make it run normanly but there still was a problem
    the result of the encryption was always the same no metter what was the original text you put in so it still gave no normal result but the decryption work 100% so that made me angry a bit cause i could nt figure the way to make it work also right well have a look maybe you ll come up with something thanks again for your time!!best regards!

  • #9
    New Coder
    Join Date
    Nov 2008
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    well based on the cesar cryptografy it is only for caps lock...chars!

  • #10
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by BISKOT188 View Post
    well i didnt tell you to believe me i just trying to learn a couple of things
    for the ascii yes i saw that page before cause i searched that well i know that not all of them are prinatable so i have to figure out a loop ..to make is run.. as far as i remember is is from 65 to 90 and 97 to 122 but i dont know how to make that loop inside this chars only ..

    and about the code i gave you my first try it makes if you think it a bit different and see all the code anyway ....

    there is an error c2016 if i remember well but i tried to do like this
    this error don't tell me anything because is compiler specific. I use gcc.

    instead of that 2 lines

    [code]

    int x;
    if (x > 'Z')
    x -= 'Z' - 'A';

    printf("\n Your encrypted text is: %x \n", buff);
    [\code]
    this code will change only once the value of x and buff is a array of chars, don't work.

    well in that way i could make it run normanly but there still was a problem
    the result of the encryption was always the same no metter what was the original text you put in so it still gave no normal result but the decryption work 100% so that made me angry a bit cause i could nt figure the way to make it work also right well have a look maybe you ll come up with something thanks again for your time!!best regards!
    best regards

  • #11
    New Coder
    Join Date
    Nov 2008
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by oesxyl View Post
    this error don't tell me anything because is compiler specific. I use gcc.


    this code will change only once the value of x and buff is a array of chars, don't work.



    best regards
    thats the reason it always show me the same result ...
    it said that the left value should be equal to the right one ..

  • #12
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by BISKOT188 View Post
    well based on the cesar cryptografy it is only for caps lock...chars!
    Code:
    #include <stdio.h>
    #include <string.h>
    
    void menu(void){
      printf("Please enter a number: \n"
             "1-Encrypt\n"
             "2-Decrypt\n"
             "3-Exit\n"
             "prompt > ");
      fflush( stdout );
    }
    
    int getchoice(void){
      char buff[BUFSIZ];
      int  choice = 0;
      do {
        menu();
        if(fgets( buff, sizeof buff, stdin ) != NULL){
          /* success reading a line, does it make sense? */
          if(sscanf( buff, "%d", &choice) != 1){
            printf("Enter a number\n");
          }
        }else{
          /* user EOF, just exit now */
          choice = 3;
        }
      }while(choice < 1 || choice > 3);
      return choice;
    }
    
    void encode(void){
      char buff[BUFSIZ];
      int i = 0;
      int shift_value;
      printf( "Doing encrypt\n" );
      printf("\nPlease enter the text you wish to encrypt: ");
      fgets(buff, sizeof(buff), stdin);
      printf("\nEnter your encryption shift value (anything from +-1 to 25): "); 
      scanf("%i", &shift_value);
      while(buff[i] != '\0'){
        if(buff[i] >= 'A' && buff[i] <= 'Z'){
          buff[i] = 'A' + (buff[i] - 'A' + shift_value) % 26;
        }
        i++; 
      }
      printf("\n Your encrypted text is: %s \n", buff);
    }
    
    void decode(void){
      char buff[BUFSIZ];
      int i = 0;
      int shift_value;
      printf( "Doing decrypt\n" );
      printf("\nPlease enter the text you wish to decrypt: ");
      fgets(buff, sizeof(buff), stdin);
      printf("\nEnter your encryption shift value (anything from +-1 to 25): "); 
      scanf ("%i", &shift_value);
    
      while(buff[i] != '\0'){
        if(buff[i] >= 'A' && buff[i] <= 'Z'){
          buff[i] = 'A' + (buff[i] - 'A' - shift_value) % 26;
        }
        i++;
      }
      printf("\nYour decrypted text is: %s \n", buff);
    }
    
    int main(){
      int choice;
      while((choice=getchoice()) != 3 ){
        if(choice == 1){
          encode();
        }else{
          if(choice == 2){
            decode();
          }
        }
      }
      return 0;
    }
    this will not encode/decode, will remain unchanged, any char which is not between 'A' and 'Z'

    best regards
    Last edited by oesxyl; 11-23-2008 at 09:09 PM.

  • #13
    New Coder
    Join Date
    Nov 2008
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    error C2446: '>' : no conversion from 'int' to 'const char *'

    error C2040: '>' : 'const char [3]' differs in levels of indirection from 'int'

    error C2106: '-=' : left operand must be l-value

    all this erros in that privius line i post the fist i could understand i think there is a need to do something like ..

    Code:
    gets_s(key,20); 
    
    for(int i=0; key[i] !='\0'; i++)
    {
    	 if(!isdigit(key[i])) 
    	 {
    		 printf ("Your key is not number! Try again \n");
    		 return;
    	 }
    }
    int k = atoi(key);

  • #14
    New Coder
    Join Date
    Nov 2008
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    damn i will go and hit my head to the wall past 3 days ..i cant figre a simple if ..thanks mate it was a big help..((

    well it s realy funny ...sometimes the easiest way to solve a problem is to try the most simple thing ....

  • #15
    New Coder
    Join Date
    Nov 2008
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    but still mate something is rong with the decryption now if you put in BOOK IT ENCRYPTS with key 20 to VIIE if you put to decrypt VIIE with key 20 it doesnt give BOOK lol


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •