我正处于学习编程的最初阶段。我与一个使用自制功能的程序一起工作。我不明白我的错误。我会很感激你的帮助。请帮我一个忙,并使用与我所处的原始阶段相称的方法来回答。我将留下我写的评论,所以你可以看到我试图通过这个或那个代码行来实现的目标。创建函数; scanf和char问题
/* Prints a user's name */
#include <stdio.h>
#include <string.h>
// prototype
void PrintName(char name);
/* this is a hint for the C saying that this function will be later specified */
int main(void)
{
char name[50];
printf("Your name: ");
scanf ("%49s", name); /* limit the number of characters to 50 */
PrintName(name);
}
// Says hello to someone by name
void PrintName(char name)
{
printf("hello, %s\n", name);
}
我得到这些错误信息:
function0.c: In function ‘main’:
function0.c:14: warning: passing argument 1 of ‘PrintName’ makes integer from pointer without a cast
function0.c: In function ‘PrintName’:
function0.c:21: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
function0.c:21: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
功能PrintName是基于以前的程序我从课程了(它采用C):
#include <stdio.h>
#include <string.h>
int main (void)
{
char name[40];
printf ("Type a name: ");
scanf ("%39s", name);
printf ("%s", name);
printf("\n");
}
这最后的程序完美运作。 我在原始程序中犯了什么错误?如果我理解正确,我的PrintName函数有问题。
,打印的名称最初计划是CS50程序的修改版本,使用CS50库:
// Prints a user's name
#include <stdio.h>
#include <cs50.h>
// prototype
void PrintName(string name);
int main(void)
{
printf("Your name: ");
string s = GetString(); //GetString is the same as scanf; it takes input from the user
PrintName(s);
}
// Says hello to someone by name
void PrintName(string name)
{
printf("hello, %s\n", name);
}
鉴于“弦”是“字符”,在C,我在我的节目字符替换字符串。 谢谢!
错误消息告诉你到底发生了什么错误:'printf'需要一个'char *'作为'%s'说明符,你提供一个'char'。你的'PrintName'需要一个'char',但是你提供了一个'char *'(或者更具体地说是一个'char [50]'衰减到'char *')。 – Kninnug
谢谢。我还不熟悉char和char *之间的区别。如果我理解正确,%s需要char *。我看到一个测试程序,它在scanf中具有%s并且具有相同的字符数组:#include int main(void) {initial; char name [80] = {0}; char age [4] = {0}; printf(“Enter your first first:”); scanf(“%c”,&initial); printf(“输入你的名字:”); 012fscanf(“%s”,name);如果(initial!= name [0]) printf(“\ n%s,你得到了最初的错误。”,name); else printf(“\ nHi,%s。您的首字母是正确的,干得好!”,名称); –
Ducol
对不起!不知道如何在评论中发布程序。我的帖子现在看起来不好。 – Ducol