2015-08-27 95 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