C 从输入比较字符串
我要求用户选择一个选项。然后,当转换为字母时,命令strcmp总是得到-1。我试图检查正在比较的内容,发现字符串得到的是“\ninput”而不是“input”。我想知道为什么会这样C 从输入比较字符串,c,alphabetical,letter,morse-code,converters,C,Alphabetical,Letter,Morse Code,Converters,我要求用户选择一个选项。然后,当转换为字母时,命令strcmp总是得到-1。我试图检查正在比较的内容,发现字符串得到的是“\ninput”而不是“input”。我想知道为什么会这样 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> static char *alfa[] = { "A", "B", "C", "
#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;
}
}
#包括
#包括
#包括
#包括
静态字符*alfa[]={
“A”,
“B”,
“C”,
“D”,
“E”,
“F”,
“G”,
“H”,
“我”,
“J”,
“K”,
“L”,
“M”,
“N”,
“O”,
“P”,
“Q”,
“R”,
“S”、“T”,
“U”,
“五”,
“W”,
“X”,
“Y”,
“Z”,
};
静态字符*莫尔斯[]={
“-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;字符字符串[100];
int cont=0;
char*v;char o='';
printf(“键入摩尔斯电码:\n”);
而(o!=“X”){
o=toupper(getc(stdin));
字符串[i]=o;
i++;
}
printf(“字符串输入:%s\n”,字符串);
while(strcmp(string,morse[cont])!=0&&cont当您调用scanf
时,它所做的只是读取一个数字。该数字之后的任何输入都留给以后的调用读取输入。由于必须按Enter键才能读取该数字,因此当您读取字符串时,它仍在缓冲区中
一种可能的解决方案可能是:
char input[100];
fgets(input,100,stdin);
sscanf(input,"%d",&entry);
也就是说,fgets
将读取整行输入,然后使用sscanf
提取数字
值得记住的是,当你在莫尔斯电码输入“X”时停止时读取莫尔斯电码时,你也会遇到这个问题