2015-08-27 128 views
1

我正处于学习编程的最初阶段。我与一个使用自制功能的程序一起工作。我不明白我的错误。我会很感激你的帮助。请帮我一个忙,并使用与我所处的原始阶段相称的方法来回答。我将留下我写的评论,所以你可以看到我试图通过这个或那个代码行来实现的目标。创建函数; 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,我在我的节目字符替换字符串。 谢谢!

+2

错误消息告诉你到底发生了什么错误:'printf'需要一个'char *'作为'%s'说明符,你提供一个'char'。你的'PrintName'需要一个'char',但是你提供了一个'char *'(或者更具体地说是一个'char [50]'衰减到'char *')。 – Kninnug

+0

谢谢。我还不熟悉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

+0

对不起!不知道如何在评论中发布程序。我的帖子现在看起来不好。 – Ducol

回答

2

你的功能PrintName正在等待一个字符作为参数,但你给char[]这就是为什么你看到这一点:

warning: passing argument 1 of ‘PrintName’ makes integer from pointer without a cast 

授予char[],因为你需要改变你的函数类似这样的参数:

void PrintName(char *name); 
2

您应该使用char *而不是char作为函数的参数。 Char是一个符号,而char *是指向字符串的指针。

1

变化void PrintName (char name);void PrintName (char *name);void PrintName (char name[]);

目前这个函数接收名字叫一个字符。你想要它接收一个字符数组。

1
void PrintName(char name); 

你函数期望character variable传递,而是你通过一个char array。因此会导致错误。

此外,%sprintf将预计char *和您通过char,从而导致另一个问题。

要纠正你的程序申报,并与参数定义函数如下 -

void PrintName(char *name); 

void PrintName(char name[]); 

双方将合作。

+0

谢谢大家!现在很清楚。感谢您的帮助! – Ducol

+0

@Ducol很高兴你的问题解决了。干杯! – ameyCU