[ create a new paste ] login | about

Link: http://codepad.org/GNvThzmx    [ raw code | output | fork ]

nilukush - C, pasted on Apr 15:
#include <stdio.h>  /* For size_t */
#include <string.h>

/* 
   Reads at most size characters into the array. 
   Stops if a newline or EOF is encountered. 
   The newline is not included in the array. 
   The array is always terminated by '\0'. 
   Returns length of the string. 
   Please note that memory allocation is callers responsibility. 
   pptr should have space for size+1 characters. 
*/ 

size_t input(char *pptr, size_t size) 
{ 
    size_t len = 0; 
	printf("\nRead string from keyboard : ");
    while(size > len) 
    {   int ch;
        ch = getchar(); 
        if(ch == '\n' || ch == EOF) break;
        printf("\nCurrent len : %d, ", len);
        printf("Before : %c, ", *pptr);
        *(pptr++) = (char)ch;
        printf("After : %c, ", *(pptr-1));
        ++len;
    } 
    *pptr = '\0'; 
    return len; 
}

int main(void)
{
    char sample[] = "some";
    int size = strlen(sample);
    char *pptr = (char*)malloc(size);
    pptr = sample;
    printf("\nSample : %s", sample);
    printf("\nSize : %d", size);
    printf("\nFinal Length : %d", input(pptr, size));
    return 0;
}


Output:
1
2
3
4
5

Sample : some
Size : 4
Read string from keyboard : 
Final Length : 0


Create a new paste based on this one


Comments: