I am writing a program that stores input from the console. To simplify it lets say I need to output what was wrote to the console.
So I have something like this:
int main()
{
char* input;
printf("Please write a bunch of stuff"); // More or less.
fgets() // Stores the input to the console in the input char*
printf(input);
}
So that is it in more or less. Just trying to give you the general ide开发者_开发知识库a. So what if they input something the size of 999999999999. How can I assign a char* to be that size dynamically.
#include <stdio.h>
int main(void)
{
char input[8192];
printf("Please type a bunch of stuff: ");
if (fgets(input, sizeof(input), fp) != 0)
printf("%s", input);
return(0);
}
That allows for a rather large space. You could check that you actually got a newline in the data.
If that's not sufficient, then investigate the POSIX 2008 function getline()
, available in Linux, which dynamically allocates memory as necessary.
Here's an example - you need to validate the input and make sure you don't overflow your buffer. In this example, I discard anything over the max length and instruct the user to try again. Another approach would be allocating a new (larger) buffer when that happened.
fgets()
second argument is the maximum number of characters you will read from the input. I'm actually accounting for the \n
in this example and getting rid of it, you may not want to do so.
#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);
}
精彩评论