예를 들어, 입력의 유효성을 검사하고 버퍼 오버플로를 방지해야합니다. 이 예제에서는 최대 길이 이상을 버리고 사용자에게 다시 시도하도록 지시합니다. 또 다른 접근법은 그럴 때 새로운 (더 큰) 버퍼를 할당하는 것입니다.
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