2014-04-30 70 views
-11

例如,假設你要求用戶輸入自己喜歡的文字和掃描。你如何能夠在Eclipse上返回這個單詞的長度?我想出了這樣的事情,但沒有完成。任何幫助將不勝感激。如何返回一行的長度?

int getLineLength(int *linelength_ptr); 

int main(void) 
{ 
char faveword[50]; 
printf("Enter your favorite word.") 
scanf("%50s", &faveword[0]); 
} 

int getLineLength(int *linelength_ptr); 
+7

你寫C#和Java代碼,但它似乎是C語言。 – ermahgerd

+0

試過保存在一個串線和returnig在getLineLength功能的字符串長度? – apomene

+1

你試過什麼部分?只是函數聲明? – const

回答

1

嘗試使用的strlen()函數:

/* strlen example */ 
#include <stdio.h> 
#include <string.h> 

int main() 
{ 
    char szInput[256]; 
    printf ("Enter a sentence: "); 
    gets (szInput); 
    printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(szInput)); 
    return 0; 
} 

http://www.cplusplus.com/reference/cstring/strlen/

+1

請不要建議人們,特別是初學者,使用'得到()'。它應該*永遠不會被使用。使用'與fgets(szInput,的sizeof szInput,標準輸入);'相反,它是更安全。 – unwind

1

編輯拍攝:我寫這個答案之前,OP移除Java標記,將會把它作爲一個參考

所以,如果你想在JAVA做到這一點,只需用掃描儀以獲取輸入和。長度()函數:

Scanner scan = new Scanner(System.in); 
System.out.print("Enter a word or phrase"); 
String phrase = scan.next(); 
int wordLength = phrase.length(); 

其中字長是包含用戶輸入

0

的長度爲提高菲利普顏的回答整數:如果你想知道是怎麼strlen作品溫控功能,這裏是你的getLineLength功能的inmplementation:

int getLineLength(char *string); 
{ 
    int length = 0 ; 
    while (*string++) 
    length++ ; 

    return length ; 
} 

順便說一句:getLineLength因爲一個字符串實際上的char陣列由零終止必須採取char*參數。