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

时间:2011-02-20 00:15:55

标签: c

如果用户输入以下示例:

My name is James.

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

4 个答案:

答案 0 :(得分:16)

尝试:

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

将80替换为小于阵列大小的80。 Check out the scanf man page for more information

答案 1 :(得分:3)

@Splat在这里有最好的答案,因为这是家庭作业,你的部分任务是使用scanf。但是,fgets更容易使用,并提供更好的控制。

关于第二个问题,您将获得带有strlen的字符串的长度,并将其存储在size_t类型的变量中。将它存储在int中是错误的,因为我们不希望有-5长度的字符串。同样,将它存储在unsigned int或其他无符号类型中是不合适的,因为我们不确切知道整数类型的大小,也不确定我们需要多大的空间来存储大小。 size_t类型作为一种类型保证适合您的系统。

答案 2 :(得分: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 :(得分:-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;
}