【问题标题】:I can't figure out strcpy我无法弄清楚 strcpy
【发布时间】: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*。下定决心——一个变量只能有一种类型。

标签: c strcpy


【解决方案1】:

c 是一个字符,而a 是一个字符串(这解释了为什么c 只能包含一个字符,以及为什么编译器会抱怨)。如果您希望 c 保存整个字符串,请将其声明为这样(就像您为 sentence 所做的那样)。

【讨论】:

    【解决方案2】:

    您已将变量 c 声明为具有 char 类型:

    char c;
    

    那么您尝试使用strcpy(c,a) -- 但是strcpy 的第一个参数期望什么类型?这是手册页中的签名:

    char *strcpy(char *dest, const char *src);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      相关资源
      最近更新 更多