2011-08-29 2 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); 
} 
관련 문제