当我使用带有空格分隔字符的strtok(str, " ");
时,当我尝试打印字符串行中的所有字符串时,它会给我几次第一个字符串。
这是我的代码:
#include<stdio.h>
#include<string.h>
void usage();
void morseText(char);
int main(int argc, char *argv[]){
char * pch;
if(argc != 3)
usage();
else {
if(strcmp(argv[1],"-m") == 0){
for(int i=0; i<strlen(argv[2]); i++){
pch = strtok(argv[2], " ,");
while (pch != NULL){
printf("%s\n", pch);
pch = strtok(NULL, " ,");
}
}
printf("morse to text\n");
}
else if(strcmp(argv[1], "-t") == 0){
printf("text to morse:\n");
for(int i=0; i<strlen(argv[2]); i++){
morseText(argv[2][i]);
}
printf("\n");
}
}
return 0;
}
void morseText(char a){
if(a>=97)
a = a - 32;
if(a == 'A')
printf(".-");
else if(a == 'B')
printf("-...");
else if(a == 'C')
printf("-.-.");
else if(a == 'D')
printf("-..");
else if(a == 'E')
printf(".");
else if(a =='F')
printf("..-.");
else if(a =='G')
printf("--.");
else if(a == 'H')
printf("....");
else if(a == 'I')
printf("..");
else if(a == 'J')
printf(".---");
else if(a == 'K')
printf("-.-");
else if(a == 'L')
printf(".-..");
else if(a == 'M')
printf("--");
else if(a == 'N')
printf("-.");
else if(a == 'O')
printf("---");
else if(a == 'P')
printf(".--.");
else if(a == 'Q')
printf("--.-");
else if(a == 'R')
printf(".-.");
else if(a == 'S')
printf("...");
else if(a == 'T')
printf("-");
else if(a == 'U')
printf("..-");
else if(a == 'V')
printf("...-");
else if(a == 'W')
printf(".--");
else if(a == 'X')
printf("-..-");
else if(a == 'Y')
printf("-.--");
else if(a == 'Z')
printf("--..");
else if(a == '0')
printf("-----");
else if(a == '1')
printf(".----");
else if(a == '2')
printf("..---");
else if(a == '3')
printf("...--");
else if(a == '4')
printf("....-");
else if(a == '5')
printf(".....");
else if(a == '6')
printf("-....");
else if(a == '7')
printf("--...");
else if(a == '8')
printf("---..");
else if(a =='9')
printf("----.");
else if(a == 32)
printf(" ");
else if(a == 13)
printf("\n");
else
printf("Not applicable char\n");
}
void usage(){
printf("Usage: ./morse -o string\n");
printf("-o could be \"-m\" from morse to text\n");
printf("-o could be \"-t\" from text to morse\n");
printf("string could be file input or direct text input\n");
printf("for example: ./morse -m \"--.\"\n");
printf("\t or ./morse -t \"aab\"\n");
}
我正在尝试编写简单的莫尔斯转换器。好奇而已。但我不明白为什么它会多次打印我的第一个论点。 结果如下 The compiled code result
我等了4个结果,因为我提供了"... .... .... ---..--"
结果。
但是代码给了我
...
....
....
---..--
...
...
这个结果。
有谁知道为什么这样工作?
提前致谢