0

I'm asking the user to select an option. Then, when converting to a letter, the command strcmp always gets -1 . I tried to check what is being compared and found out that the String is getting "\ninput" instead of "input". I wonder why this happens

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

static char *alfa[] = {
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S", "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
};

static char *morse[] = {
    ".-X",   //A
    "-...X", //B
    "-.-.X", //C
    "-..X",  //D
    ".X",    //E
    "..-.X", //F
    "--.X",  //G
    "....X", //H
    "..X",   //I
    ".---X", //J
    "-.-X",  //K
    ".-..X", //L
    "--X",   //M
    "-.X",   //N
    "---X",  //O
    ".--.X", //P
    "--.-X", //Q
    ".-.X",  //R
    "...X",  //S
    "-X",    //T
    "..-X",  //U
    "...-X", //V
    ".--X",  //W
    "-..-X", //X
    "-.--X", //Y
    "--..X" //Z
};

void morseToAlfa(){
    int i=0;char string[100];
    int cont=0;
    char*v;char o = ' ';
    printf("Type morse code:\n") ;
    while (o != 'X'){
        o = toupper(getc(stdin));
        string[i] = o;
        i++;
    }

    printf("String input: %s\n",string);
    while(strcmp(string,morse[cont]) != 0 && cont<25){
        printf("String[] : %s\n'",string);
        printf("*Morse[]: %s\n",morse[cont]);
        printf("Case %d:    %d\n",cont,i);
        cont++;
        printf("\n\n"); 
    }

    printf("Cont: %d\n",cont);
    printf("*Morse[]: %s\n",morse[cont]);
    printf("*Alfa[]: %s\n",alfa[cont]);
}

int main(int argc, char *argv[]) {
    int entry;
    char op=' ';

    while(op){ 
        printf("\nType 1 to convert to alphabet, morse must have end with 'X' (eg. .-X)\n");
        printf("\nType 0 to close\n");
        scanf("%d",&entry); 
        if(entry == 1) morseToAlfa();
        if(entry == 0) return 0;

    }

}

NOTE: If you just put the function with no scan, it works successfully. So the problem might be on the second scanning .

Barmar
  • 741,623
  • 53
  • 500
  • 612
BCM
  • 1
  • 1

1 Answers1

0

When you call scanf all it is doing is reading in a number. Any input after the number is left for future calls to read in input. Since you have to press Enter for the number to be read it is still in the buffer when you come to read in your string.

One possible solution might be this:

char input[100];
fgets(input,100,stdin);
sscanf(input,"%d",&entry);

which is to use the fact that fgets will read in a whole line of input and then you're extracting the number using sscanf.

It's worth remembering that you'll also have that problem when you read in the morse string as you're stopping when they enter an "X"

Chris Turner
  • 8,082
  • 1
  • 14
  • 18