我是C编程的初学者。我编写了将字符串转换为带有点和短划线的字母字符串的程序。但printf()无法正常工作。我写错了什么?(老实说这个程序使用处理器ATMega。但是我的代码中存在主要问题,所以不要注意它)
#include <avr/io.h>
#include <util/delay.h>
#include <stdio.h>
#include <string.h>
int main()
{
char morze[] = "";
char buf[] ="Name Surname Patronymic";
int a = 0;
char *p = strtok (buf, " ");
char *each_word[3];
while (p != NULL)
{
each_word[a++] = p;
p = strtok (NULL, " ");
}
for(int i = 0; i < strlen(each_word); i++){
for(int j = 0; j < strlen(each_word[i]); j++){
if(tolower(each_word[i][j]) == "a") strcat(morze,".- ");
else if(tolower(each_word[i][j]) == "b") strcat(morze,"-... ");
else if(tolower(each_word[i][j]) == "c") strcat(morze,"-.-. ");
else if(tolower(each_word[i][j]) == "d") strcat(morze,"-.. ");
else if(tolower(each_word[i][j]) == "e") strcat(morze,". ");
else if(tolower(each_word[i][j]) == "f") strcat(morze,"..-. ");
else if(tolower(each_word[i][j]) == "g") strcat(morze,"--. ");
else if(tolower(each_word[i][j]) == "h") strcat(morze,".... ");
else if(tolower(each_word[i][j]) == "i") strcat(morze,".. ");
else if(tolower(each_word[i][j]) == "j") strcat(morze,".--- ");
else if(tolower(each_word[i][j]) == "k") strcat(morze,"-.- ");
else if(tolower(each_word[i][j]) == "l") strcat(morze,".-.. ");
else if(tolower(each_word[i][j]) == "m") strcat(morze,"-- ");
else if(tolower(each_word[i][j]) == "n") strcat(morze,"-. ");
else if(tolower(each_word[i][j]) == "o") strcat(morze,"--- ");
else if(tolower(each_word[i][j]) == "p") strcat(morze,".--. ");
else if(tolower(each_word[i][j]) == "q") strcat(morze,"--.- ");
else if(tolower(each_word[i][j]) == "r") strcat(morze,".-. ");
else if(tolower(each_word[i][j]) == "s") strcat(morze,"... ");
else if(tolower(each_word[i][j]) == "t") strcat(morze,"- ");
else if(tolower(each_word[i][j]) == "u") strcat(morze,"..- ");
else if(tolower(each_word[i][j]) == "v") strcat(morze,"...- ");
else if(tolower(each_word[i][j]) == "w") strcat(morze,".-- ");
else if(tolower(each_word[i][j]) == "x") strcat(morze,"-..- ");
else if(tolower(each_word[i][j]) == "y") strcat(morze,"-.-- ");
else if(tolower(each_word[i][j]) == "z") strcat(morze,"--.. ");
}
}
printf(buf);
int b = 0;
char *q = strtok (morze, " ");
char *each_letter[3];
while (q != NULL)
{
each_letter[b++] = q;
q = strtok (NULL, " ");
}
for(int i = 0; i < strlen(each_letter); i++){
for(int j = 0; j < strlen(each_letter[i]); j++){
if(each_letter[i][j] == ".") {printf("1");}
else if(each_letter[i][j] == "-") {printf("2");}
}
}
}
答案 0 :(得分:0)
你做的任何事情都是错误的,因为morze
不足以连接到它,请尝试
char morze[100 /* Large enough size */] = "";
代替。
由于默认行为是分配包含单个字节'\0'
的大小为1的数组,因此无法调整此类数组的大小。
此外,c中的==
运算符未进行字符串比较,您需要使用strcmp()
来比较两个字符串。但是,无论如何你都不需要比较单个字符,而是
switch (character) {
case 'a':
case 'b':
case ...:
break;
}