Home > Software design >  How to use strdup with user input?
How to use strdup with user input?

Time:11-10

#include <stdio.h>
#include <string.h>

int main()
{
    
    char cipher[5][5] = {
                    {'a', 'b', 'c', 'd', 'e'},
                    {'f', 'g', 'h', 'i', 'k'},
                    {'l', 'm', 'n', 'o', 'p'},
                    {'q', 'r', 's', 't', 'u'},
                    {'v', 'w', 'x', 'y', 'z'}
                        };
                    
    
    char cm;
    char *original;
    char *portion;
    printf("Enter ciphered message: ");
    scanf("%s", &cm);


    original = strdup(&cm);
    portion = strtok(original, "-");

    
    while (portion != NULL){

        int i = portion[0]-'0';
        int j = portion[1]-'0';

        printf("%c", cipher[i][j]);
        portion = strtok(NULL, "-");
        
        }
    

    return 0;
}

Hello, I'm a new computer science student and I'm already having a problem. I'm writing a polybius cypher and I can't seem to get the user input saved correctly to use at strdup

With input i.e.: 00-11-22-33-44 I should receive "agntz" but I can't get it to print. I'm new here so I apologize if I haven't formatted my question correctly.

CodePudding user response:

The main issue is that you char cm is a single character but you want to read a string char *cm. If your scanf() supports the optional m character then the easiest option to have it allocate your string for you:

#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <string.h>

int main(void) {
    char cipher[5][5] = {
        {'a', 'b', 'c', 'd', 'e'},
        {'f', 'g', 'h', 'i', 'k'},
        {'l', 'm', 'n', 'o', 'p'},
        {'q', 'r', 's', 't', 'u'},
        {'v', 'w', 'x', 'y', 'z'}
    };
    char *cm;
    char *original;
    char *portion;
    printf("Enter ciphered message: ");
    scanf("%ms", &cm);
    original = strdup(cm);
    portion = strtok(original, "-");
    while (portion != NULL){
        int i = portion[0]-'0';
        int j = portion[1]-'0';
        printf("%c", cipher[i][j]);
        portion = strtok(NULL, "-");
    }
    printf("\n");
}

and the you are now getting the expected output:

Enter ciphered message: 00-11-22-33-44
agntz

It would be a good idea to check that portion[0] and portion[1] are indeed numbers (for instance by usingisdigit()) to avoid out of bound access of cipher. Also check that you only get two digits in portion (strlen(portion) == 2).

Is missing j in the cipher on purpose?

You can refactor the above along these lines:

#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <string.h>

int main(void) {
    char cipher[] = "abcdefghiklmnopqrstuvwxyz";
    char *cm;
    printf("Enter ciphered message: ");
    scanf("%ms", &cm);
    for(char *portion = strtok(cm, "-"); portion; portion = strtok(NULL, "-")) {
        int i = portion[0]-'0';
        int j = portion[1]-'0';
        printf("%c", cipher[5*i j]);
    }
    printf("\n");
}
  • Related