如何在C语言中使用scanf输入包括空格在内的字符串

8

如果用户输入:

我的名字是詹姆斯。

使用 scanf,我必须打印出整行内容,即 我的名字是詹姆斯。,然后我需要获取这个输入字符串的长度并将其存储在一个 int 变量中。


7
在现实生活中,你可以简单地使用 fgets - Matteo Italia
3
在现实生活中,你也会使用谷歌。与此完全相同的副本 - Reno
4个回答

16

1
"%80[^\n]" 应该足够了,因为以文本模式打开的 FILE *(如 stdin)将把 Windows/其他换行符转换为 \n 字符。 - Chris Lutz

3
@Splat在这里给出了最好的答案,因为这是一份作业,你的任务之一就是使用scanf。然而,fgets更容易使用并提供更精细的控制。
至于你的第二个问题,你可以使用strlen来获取字符串的长度,并将其存储在size_t类型的变量中。将其存储在int中是错误的,因为我们不希望有长度为-5的字符串。同样,将其存储在unsigned int或其他无符号类型中也不合适,因为我们不知道整数类型有多大,也不知道我们需要多少空间来存储大小。size_t类型存在是为了保证在您的系统中具有正确的大小。

0
#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

3
void main()是一个函数的开头,它表示该函数没有返回值。这个问题可能来自2011年左右,那时候人们可能会使用clrscr()函数来清空屏幕,现在一般不再需要这样做了。 - Chris Lutz
1
我在TURBO C中执行了这个程序,所以它才会这样。 - Vishwanath Dalvi

-1
#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
@DaV 这个链接包含了有关 fflush 的完整细节 https://www.geeksforgeeks.org/use-fflushstdin-c/ - Rohit Kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接