我正處於學習編程的最初階段。我與一個使用自制功能的程序一起工作。我不明白我的錯誤。我會很感激你的幫助。請幫我一個忙,並使用與我所處的原始階段相稱的方法來回答。我將留下我寫的評論,所以你可以看到我試圖通過這個或那個代碼行來實現的目標。創建函數; 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