Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 我试图将第一个单词提取为字符串,并将其用作字符_C - Fatal编程技术网

C 我试图将第一个单词提取为字符串,并将其用作字符

C 我试图将第一个单词提取为字符串,并将其用作字符,c,C,在这里,我试图输入名字和姓氏作为“Firstname Lastname”。 我想得到“Lastname,FN”的输出,其中FN是名字的第一个字母 示例:Input=“James Garcia”;Output=“Garcia,J.” 请在我的代码中查找错误 #include <stdio.h> int main () { char fn[20],ln[20]; printf("Enter a first name and a last name:"); sc

在这里,我试图输入名字和姓氏作为“Firstname Lastname”。 我想得到“Lastname,FN”的输出,其中FN是名字的第一个字母

示例:Input=“James Garcia”;Output=“Garcia,J.”

请在我的代码中查找错误

#include <stdio.h>

int main () {
    char fn[20],ln[20];

    printf("Enter a first name and a last name:");
    scanf("%c %s",&fn,&ln);

    printf("%s, %c.",ln,fn);


    return(0);
}
#包括
int main(){
char-fn[20],ln[20];
printf(“输入名字和姓氏:”);
scanf(“%c%s”,&fn,&ln);
printf(“%s,%c.”,ln,fn);
返回(0);
}
您想要这个:

printf("Enter a first name and a last name:");
scanf("%s %s", fn, ln);        // you are reading two strings,
                               // not one char and one string
printf("%s, %c.", ln, fn[0]);  // you print one string and one char
                               // not two chars

免责声明:这是一个过于简化的代码,不做任何简短的错误检查。

请在我的代码中查找错误。
…嗯..不。'。欢迎来到堆栈溢出!您似乎忘记启用一组好的警告。对于GCC,我建议至少使用
-Wall-Wextra-Wwrite strings
;还可以考虑<代码> -WPDEANTIC- WARIX界限<代码>以识别其他常见错误。请投票表决,但也请注意使用<代码> SCANF:谢谢“JabBrWOKKY”。但是你能告诉我为什么我们要在第二个printf中把[0]放在fn后面来打印字符。@NikhilBoddupalli你需要阅读C教科书中关于数组和指针的章节以及关于字符串的章节
fn
是第一个字符的地址
fn[0]
是第一个字符,
fn[1]
是第二个字符等。至少,我认为这应该在依赖具有有效值的变量之前检查
scanf()
的返回值,还应该包括大小限制,以避免打开缓冲区溢出。