Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read unlimited characters in C

How to read unlimited characters into a char* variable without specifying the size?

For example, say I want to read the address of an employee that may also take multiple lines.

like image 312
PrithviRaj Avatar asked Mar 24 '10 05:03

PrithviRaj


People also ask

How do you read a character in C?

Read String from the user You can use the scanf() function to read a string. The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).

Can I modify string in C?

The only difference is that you cannot modify string literals, whereas you can modify arrays. Functions that take a C-style string will be just as happy to accept string literals unless they modify the string (in which case your program will crash).

Does C have a string library?

h is the header in the C standard library for the C programming language which contains macro definitions, constants and declarations of functions and types used not only for string handling but also various memory handling functions; the name is thus something of a misnomer. Functions declared in string.

How do you take string input of an unknown length in C?

For this problem, there is a format specifier %s by which we can read a string of unknown length and we don't need looping to read and print the string in the code. It results in less time taken for compiling the code by the compiler.


2 Answers

You have to start by "guessing" the size that you expect, then allocate a buffer that big using malloc. If that turns out to be too small, you use realloc to resize the buffer to be a bit bigger. Sample code:

char *buffer;
size_t num_read;
size_t buffer_size;

buffer_size = 100;
buffer = malloc(buffer_size);
num_read = 0;

while (!finished_reading()) {
    char c = getchar();
    if (num_read >= buffer_size) {
        char *new_buffer;

        buffer_size *= 2; // try a buffer that's twice as big as before
        new_buffer = realloc(buffer, buffer_size);
        if (new_buffer == NULL) {
            free(buffer);
            /* Abort - out of memory */
        }

        buffer = new_buffer;
    }
    buffer[num_read] = c;
    num_read++;
}

This is just off the top of my head, and might (read: will probably) contain errors, but should give you a good idea.

like image 127
Dean Harding Avatar answered Sep 18 '22 03:09

Dean Harding


Just had to answer Ex7.1, pg 330 of Beginning C, by Ivor Horton, 3rd edition. Took a couple of weeks to work out. Allows input of floating numbers without specifying in advance how many numbers the user will enter. Stores the numbers in a dynamic array, and then prints out the numbers, and the average value. Using Code::Blocks with Ubuntu 11.04. Hope it helps.

/*realloc_for_averaging_value_of_floats_fri14Sept2012_16:30  */

#include <stdio.h>
#include <stdlib.h>
#define TRUE 1

int main(int argc, char ** argv[])
{
    float input = 0;
    int count=0, n = 0;
    float *numbers = NULL;
    float *more_numbers;
    float sum = 0.0;

    while (TRUE)
    {
        do
        {
            printf("Enter an floating point value (0 to end): ");
            scanf("%f", &input);
            count++;
            more_numbers = (float*) realloc(numbers, count * sizeof(float));
            if ( more_numbers != NULL )
            {
                numbers = more_numbers;
                numbers[count - 1] = input;
            }
            else
            {
                free(numbers);
                puts("Error (re)allocating memory");
                exit(TRUE);
            }
        } while ( input != 0 );

        printf("Numbers entered: ");
        while( n < count )
        {
            printf("%f ", numbers[n]);  /* n is always less than count.*/
            n++;
        }
        /*need n++ otherwise loops forever*/
        n = 0;
        while( n < count )
        {
            sum += numbers[n];      /*Add numbers together*/
            n++;
        }
        /* Divide sum / count = average.*/
        printf("\n Average of floats = %f \n", sum / (count - 1));
    }
    return 0;
}

/* Success Fri Sept 14 13:29 . That was hard work.*/
/* Always looks simple when working.*/
/* Next step is to use a function to work out the average.*/
/*Anonymous on July 04, 2012*/
/* http://www.careercup.com/question?id=14193663 */
like image 24
Malcolm Jackson Avatar answered Sep 22 '22 03:09

Malcolm Jackson