C语言 如何在c中使用scanf输入字符串,包括空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5054414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to input a string using scanf in c including whitespaces
提问by shobhnit
Example if user enters:
用户输入的示例:
My name is James.
My name is James.
Using scanf, I have to print the full line, i.e. My name is James., then I have to get the length of this entered string and store it in an intvariable.
使用scanf,我必须打印整行,即My name is James.,然后我必须获得这个输入字符串的长度并将其存储在一个int变量中。
回答by Splat
Try:
尝试:
scanf("%80[^\r\n]", string);
Replace 80 with 1 less that the size of your array. Check out the scanf man page for more information
将 80 替换为比数组大小少 1 的值。 查看 scanf 手册页了解更多信息
回答by Chris Lutz
@Splathas the best answer here, since this is homework and part of your assignment is to use scanf. However, fgetsis much easier to use and offers finer control.
@Splat在这里有最好的答案,因为这是家庭作业,您的任务的一部分是使用scanf. 但是,fgets它更易于使用并提供更精细的控制。
As to your second question, you get the length of a string with strlen, and you store it in a variable of type size_t. Storing it in an intis wrong, because we don't expect to have strings of -5 length. Likewise, storing it in an unsigned intor other unsigned type is inappropriate because we don't know exactly how big an integral type is, nor exactly how much room we need to store the size. The size_ttype exists as a type that is guaranteed to be the right size for your system.
至于您的第二个问题,您使用 获得字符串的长度,strlen并将其存储在类型为 的变量中size_t。将它存储在 an 中int是错误的,因为我们不希望有 -5 长度的字符串。同样,将它存储在一个unsigned int或其他无符号类型中是不合适的,因为我们不确切知道整数类型有多大,也不确切知道我们需要多少空间来存储大小。该size_t类型作为一种类型存在,可保证其大小适合您的系统。
回答by mr_eclair
#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
回答by Rohit Kumar
#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;
}

