2011-08-29 58 views
0

我正在编写一个存储控制台输入的程序。为了简化它,可以说我需要输出写到控制台的内容。C基于控制台输入的动态数组

所以我有这样的事情:

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); 
} 

所以这是它或多或少。只是想给你一个总的想法。那么,如果他们输入大小为999999999999的东西呢?我怎样才能将一个char *指定为动态大小。

+1

张贴实际的代码,而不是代码将无法正常工作(有输入变量没有后盾内存)会是一个更好的主意... –

+0

放入健全的最大值为你处理一下,并把它当作一个否则错误。 –

+1

有一些限制,如控制台实际接受的长度。只是分配字符串的长度并确保分配没有失败 – fazo

回答

1
#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); 
} 

这允许一个相当大的空间。你可以检查你是否真的在数据中有一个换行符。

如果这还不够,请调查在Linux中可用的POSIX 2008函数getline(),该函数在必要时动态分配内存。

0

下面是一个示例 - 您需要验证输入并确保不会溢出缓冲区。在这个例子中,我丢弃超过最大长度的任何东西,并指示用户再次尝试。另一种方法是在发生时分配一个新的(更大的)缓冲区。

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); 
}