【发布时间】:2015-11-22 01:38:19
【问题描述】:
我正处于学习编程的最初阶段。我正在使用一个使用自制功能的程序。我不明白我的错误。我会很感激你的帮助。请帮我一个忙,并使用与我所处的原始阶段相称的方法来回答。我要离开我写的 cmets,所以你可以通过这个或那个代码行看到我想要实现的目标。
/* 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);
}
鉴于“string”在 C 中是“char”,我在程序中将 string 替换为 char。 谢谢!
【问题讨论】:
-
错误消息告诉您究竟出了什么问题:
printf期望char *用于%s说明符,您提供char。你的PrintName需要一个char,但你提供了一个char *(或者更具体地说是一个衰减为char *的char[50])。 -
谢谢。我还不熟悉 char 和 char* 之间的区别。如果我理解正确,%s 需要 char*。我看到一个测试程序在 scanf 中有 %s 和相同的 char 数组:#include
int main(void) { char initial = ' ';字符名称[80] = { 0 };字符年龄[4] = { 0 }; printf("请输入您的姓名首字母:"); scanf("%c", &initial ); printf("请输入您的名字:"); scanf("%s", name ); if(initial != name[0]) printf("\n%s,you got your initial wrong.", name); else printf("\nHi, %s。你的名字首字母是正确的。干得好!", name ); -
对不起!不知道如何在 cmets 中发布程序。我的帖子现在看起来很糟糕。
-
char是一个字符,而char*是一个指向char的指针。用反引号 (`) 包围代码以格式化为代码。是的,%s在scanf和printf中都需要char*。请记住,无论何时将数组传递给函数,实际上都是传递数组第一个元素的地址。