【发布时间】:2015-01-21 20:04:20
【问题描述】:
这是一个未完成的代码,用于将字母数字字符转换为摩尔斯电码。到目前为止,只有字符“A”在集合中。我似乎无法将“a”的摩尔斯电码字符串复制到变量“c”中。编译器告诉我,传递 strcpy 的参数 1 会生成来自整数的指针,而无需强制转换。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(){
char c; /* variable to hold character input by user */
char sentence[ 80 ]; /* create char array */
int i = 0; /* initialize counter i */
const char *a = ".- ";
/* prompt user to enter line of text */
puts( "Enter a line of text:" );
/* use getchar to read each character */
while ( ( c = getchar() ) != '\n') {
c = toupper(c);
switch (c){
case 'A':
strcpy(c, a);
break
}
sentence[ i++ ] = c;
} /* end while */
sentence[ i ] = '\0'; /* terminate string */
/* use puts to display sentence */
puts( "\nThe line entered was:" );
puts( sentence );
return 0;
}
【问题讨论】:
-
getchar返回一个int(不是char),更改为int c;,strcpy想要一个char *(不是char)作为第一个参数 -
您的
strcpy的目标是char。它必须是char *从一开始就是错误的。 -
strcpy(不是 strcopy)将字符串复制到字符串,而不是将字符串复制到 char。 -
C 被声明为
char,但是你从getchar()分配它,它返回一个int,然后你将它传递给strcpy(),它需要一个char*。下定决心——一个变量只能有一种类型。