Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何返回行的长度?_C - Fatal编程技术网

C 如何返回行的长度?

C 如何返回行的长度?,c,C,例如,假设您要求用户输入他们最喜欢的单词并进行扫描。如何在Eclipse上返回该单词的长度?我想到了这样的东西,但它并不完整。任何帮助都将不胜感激 int getLineLength(int *linelength_ptr); int main(void) { char faveword[50]; printf("Enter your favorite word.") scanf("%50s", &faveword[0]); } int getLineLength(int *line

例如,假设您要求用户输入他们最喜欢的单词并进行扫描。如何在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);
尝试使用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;
}
Scanner scan = new Scanner(System.in);
System.out.print("Enter a word or phrase");
String phrase = scan.next();
int wordLength = phrase.length();
/*斯特伦示例*/
#包括
#包括
int main()
{
字符输入[256];
printf(“输入一个句子:”);
获取(szInput);
printf(“输入的句子长度为%u个字符。\n”,(无符号)strlen(szInput));
返回0;
}

摘自

编辑:我在OP删除java标记之前写下了这个答案,将其作为参考

因此,如果您想在JAVA中实现这一点,只需使用Scanner获取输入和.length()函数:

/* 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;
}
Scanner scan = new Scanner(System.in);
System.out.print("Enter a word or phrase");
String phrase = scan.next();
int wordLength = phrase.length();

其中,wordLength是一个包含用户输入长度的整数,以增强Phillip Ngan的回答:如果您想知道
strlen
是如何工作的,下面是
getLineLength
函数的一个实现:

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

  return length ;  
}

顺便说一句:
getLineLength
必须采用
char*
参数,因为字符串实际上是一个以零结尾的
char
数组。

您编写了c和java标记,但它似乎是c语言。您尝试过将行保存在字符串中并在getLineLength函数中返回字符串长度吗?您尝试的部分在哪里??只是函数声明??请不要建议人们,尤其是初学者,使用
get()
。永远不要使用它。使用
fgets(szInput,szInput的大小,stdin)