如何在c中使用scanf输入字符串,包括空格

用户输入的示例:

My name is James.

使用scanf,我必须打印整行,即My name is James. ,然后我必须得到这个输入字符串的长度并将其存储在一个int变量中。

尝试:

 scanf("%80[^\r\n]", string); 

将80替换为小于arrays大小的80。 有关更多信息,请查看scanf手册页

@Splat在这里有最好的答案,因为这是家庭作业,你的任务的一部分是使用scanf 。 但是, 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 
 #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; }