【发布时间】:2019-02-06 12:49:04
【问题描述】:
我要求用户选择一个选项。然后,当转换为字母时,命令 strcmp 总是得到 -1 。我试图检查正在比较的内容,发现字符串正在获取“\ninput”而不是“input”。我想知道为什么会发生这种情况
#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;
}
}
注意:如果你只是把函数不扫描,它就可以成功。所以问题可能出在第二次扫描上。
【问题讨论】:
标签: c alphabetical letter morse-code converters