如果用户输入:
我的名字是詹姆斯。
使用 scanf,我必须打印出整行内容,即 我的名字是詹姆斯。
,然后我需要获取这个输入字符串的长度并将其存储在一个 int
变量中。
如果用户输入:
我的名字是詹姆斯。
使用 scanf,我必须打印出整行内容,即 我的名字是詹姆斯。
,然后我需要获取这个输入字符串的长度并将其存储在一个 int
变量中。
"%80[^\n]"
应该足够了,因为以文本模式打开的 FILE *
(如 stdin
)将把 Windows/其他换行符转换为 \n
字符。 - Chris Lutzscanf
。然而,fgets
更容易使用并提供更精细的控制。strlen
来获取字符串的长度,并将其存储在size_t
类型的变量中。将其存储在int
中是错误的,因为我们不希望有长度为-5的字符串。同样,将其存储在unsigned int
或其他无符号类型中也不合适,因为我们不知道整数类型有多大,也不知道我们需要多少空间来存储大小。size_t
类型存在是为了保证在您的系统中具有正确的大小。#include "stdio.h"
#include "conio.h"
void main()
{
char str[20];
int i;
clrscr();
printf("Enter your string");
scanf("%[^\t\n]s",str); --scanf to accept multi-word string
i = strlen(str); -- variable i to store length of entered string
printf("%s %d",str,i); -- display the entered string and length of string
getch();
}
output :
enter your string : My name is james
display output : My name is james 16
void main()
是一个函数的开头,它表示该函数没有返回值。这个问题可能来自2011年左右,那时候人们可能会使用clrscr()
函数来清空屏幕,现在一般不再需要这样做了。 - Chris Lutz#include "stdio.h"
int main()
{
char str[20];
int i,t;
scanf("%d",&t);
while(t--){
fflush(stdin);
scanf(" %[^\t\n]s",str);// --scanf to accept multi-word string
i = strlen(str);// -- variable i to store length of entered string
printf("%s %d\n",str,i);// -- display the entered string and length of string
}
return 0;
}
fflush(stdin)
是未定义行为。 - DaV
fgets
。 - Matteo Italia