下面是一个示例 - 您需要验证输入并确保不会溢出缓冲区。在这个例子中,我丢弃超过最大长度的任何东西,并指示用户再次尝试。另一种方法是在发生时分配一个新的(更大的)缓冲区。
fgets()
第二个参数是您将从输入中读取的最大字符数。我实际上在这个例子中占了\n
,并且摆脱它,你可能不想这样做。
#include <stdio.h>
#include <string.h>
void getInput(char *question, char *inputBuffer, int bufferLength)
{
printf("%s (Max %d characters)\n", question, bufferLength - 1);
fgets(inputBuffer, bufferLength, stdin);
if (inputBuffer[strlen(inputBuffer) -1] != '\n')
{
int dropped = 0;
while (fgetc(stdin) != '\n')
dropped++;
if (dropped > 0) // if they input exactly (bufferLength - 1) characters, there's only the \n to chop off
{
printf("Woah there partner, your input was over the limit by %d characters, try again!\n", dropped);
getInput(question, inputBuffer, bufferLength);
}
}
else
{
inputBuffer[strlen(inputBuffer) -1] = '\0';
}
}
int main()
{
char inputBuffer[10];
getInput("Go ahead and enter some stuff:", inputBuffer, 10);
printf("Okay, I got: %s\n",inputBuffer);
return(0);
}
张贴实际的代码,而不是代码将无法正常工作(有输入变量没有后盾内存)会是一个更好的主意... –
放入健全的最大值为你处理一下,并把它当作一个否则错误。 –
有一些限制,如控制台实际接受的长度。只是分配字符串的长度并确保分配没有失败 – fazo