C语言 如何读取用户在 C 中输入的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4023895/
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 do I read a string entered by the user in C?
提问by Peeyush
I want to read the name entered by my user using C programmes.
我想使用 C 程序读取我的用户输入的名称。
For this I wrote:
为此,我写道:
char name[20];
printf("Enter name: ");
gets(name);
But using getsis not good, so what is a better way?
但是使用gets不好,那么有什么更好的方法呢?
回答by paxdiablo
You should neveruse gets(or scanfwith an unbounded string size) since that opens you up to buffer overflows. Use the fgetswith a stdinhandle since it allows you to limit the data that will be placed in your buffer.
您永远不应该使用gets(或scanf使用无界的字符串大小),因为这会导致缓冲区溢出。使用fgets带有stdin句柄的 ,因为它允许您限制将放置在缓冲区中的数据。
Here's a little snippet I use for line input from the user:
这是我用于用户行输入的小片段:
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '// Test program for getLine().
int main (void) {
int rc;
char buff[10];
rc = getLine ("Enter string> ", buff, sizeof(buff));
if (rc == NO_INPUT) {
// Extra NL since my system doesn't output that on EOF.
printf ("\nNo input\n");
return 1;
}
if (rc == TOO_LONG) {
printf ("Input too long [%s]\n", buff);
return 1;
}
printf ("OK [%s]\n", buff);
return 0;
}
';
return OK;
}
This allows me to set the maximum size, will detect if too much data is entered on the line, and will flush the rest of the line as well so it doesn't affect the next input operation.
这允许我设置最大大小,将检测是否在行上输入了太多数据,并将刷新行的其余部分,因此它不会影响下一个输入操作。
You can test it with something like:
您可以使用以下内容对其进行测试:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *buffer = NULL;
int read;
unsigned int len;
read = getline(&buffer, &len, stdin);
if (-1 != read)
puts(buffer);
else
printf("No line read...\n");
printf("Size read: %d\n Len: %d\n", read, len);
free(buffer);
return 0;
}
回答by joaopauloribeiro
I think the best and safest way to read strings entered by the user is using getline()
我认为读取用户输入的字符串的最佳和最安全的方法是使用 getline()
Here's an example how to do this:
以下是如何执行此操作的示例:
char*string_acquire(char*s,int size,FILE*stream){
int i;
fgets(s,size,stream);
i=strlen(s)-1;
if(s[i]!='\n') while(getchar()!='\n');
if(s[i]=='\n') s[i]='#include <stdio.h>
char *
fgetln(FILE *stream, size_t *len);
';
return s;
}
回答by jamesdlin
On a POSIX system, you probably should use getlineif it's available.
在 POSIX 系统上,getline如果可用,您可能应该使用它。
You also can use Chuck Falconer's public domain ggetsfunction which provides syntax closer to getsbut without the problems. (Chuck Falconer's website is no longer available, although archive.org has a copy, and I've made my own page for ggets.)
您还可以使用 Chuck Falconer 的公共领域ggets函数,它提供更接近gets但没有问题的语法。(Chuck Falconer 的网站不再可用,尽管archive.org 有一个副本,而且我已经为 ggets创建了自己的页面。)
回答by faber
I found an easy and nice solution:
我找到了一个简单而好的解决方案:
size_t line_len;
const char *line = fgetln(stdin, &line_len);
it's based on fgets but free from '\n' and stdin extra characters (to replace fflush(stdin) that doesn't works on all OS, useful if you have to acquire strings after this).
它基于 fgets,但没有 '\n' 和 stdin 额外字符(替换不适用于所有操作系统的 fflush(stdin),如果您必须在此之后获取字符串,则很有用)。
回答by wonder.mice
On BSD systems and Android you can also use fgetln:
在 BSD 系统和 Android 上,您还可以使用fgetln:
#define SIZE 100
....
char str[SIZE];
scanf(" %99[^\n]", str);
/* Or even you can do it like this */
scanf(" %99[a-zA-Z0-9 ]", str);
Like so:
像这样:
scanf("%[^\n]",name);
The lineis not null terminated and contains \n(or whatever your platform is using) in the end. It becomes invalid after the next I/O operation on stream. You are allowed to modify the returned linebuffer.
该line不是空终止,并包含\n(或任何平台使用)到底。在流上的下一个 I/O 操作之后它变得无效。您可以修改返回的line缓冲区。
回答by wonder.mice
Using scanfremoving any blank spaces before the string is typed and limiting the amount of characters to be read:
scanf在输入字符串之前使用删除任何空格并限制要读取的字符数:
If you do not limit the amount of characters to be read with scanfit can be as dangerous as gets
如果您不限制要读取的字符数量,scanf则可能会像gets
回答by wonder.mice
You can use scanf function to read string
您可以使用 scanf 函数读取字符串
##代码##i don't know about other better options to receive string,
我不知道接收字符串的其他更好的选择,

