我想使用 C 程序读取我的用户输入的名称。
为此我写道:
char name[20];
printf("Enter name: ");
gets(name);
但是使用gets
并不好,那么有什么更好的方法呢?
最佳答案
您应该永远不要使用gets
(或具有无限制字符串大小的scanf
),因为这会导致缓冲区溢出。将 fgets
与 stdin
句柄一起使用,因为它允许您限制将放置在缓冲区中的数据。
这是我用于用户行输入的一个小片段:
#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] = '\0';
return OK;
}
这允许我设置最大大小,将检测是否在该行中输入了太多数据,并将清空该行的其余部分,这样它就不会影响下一个输入操作。
你可以用类似的东西来测试它:
// 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;
}
关于c - 如何读取用户在 C 中输入的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4023895/