P.Hajare
P.Hajare

Reputation: 17

Accepting a string with spaces

How to dynamically accept a string with spaces? I had tried gets(), but it is not working, and I don't want to take input from file. I want to accept a string without specifying string size.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char *accept()
{
    char *s;
    s = (char *)malloc(sizeof(char));
    gets(s);
    return s;
}

int main()
{
    char *str;
    printf("\nEnter`enter code here` one string");
    str = accept();
}

Upvotes: 0

Views: 133

Answers (3)

roottraveller
roottraveller

Reputation: 8232

Define the approximate size of user input by

#define LENGTH 30

char *accept(){
    char *s = (char*)malloc(sizeof(char)*LENGTH); 
    scanf("%29[0-9a-zA-Z ]", s); 
   //scanf("%[^\n]%*s", s); //or this
    return s;
}

Note that the 29 is the maximum number of characters which will be read, so s has to point to a buffer of size LENGTH-1 at least.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206567

I want to accept string without specifying sting size.

  1. Start with a hard code number as the initial size of the string.
  2. Read characters one by one. Add the characters to the string. If the number of characters in the line exceeds the current size, increase the size of the string.

Here's such a function:

char *accept()
{
   // Initial size of the string.
   int size = 256;
   int c;
   int index = 0;

   char* s = malloc(size);
   if ( s == NULL )
   {
      return NULL;
   }

   while ( (c = getchar()) != EOF && c != '\n')
   {
      // We need one character for the terminating null character
      // Hence, if index is equal to (size-1), we need to resize the
      // string.
      if ( index == size - 1)
      {
         // Resize the string.
         size = size * 2;
         s = realloc(s, size);
         if ( s == NULL )
         {
            return NULL;
         }
      }
      s[index] = c;
      ++index;
   }

   // NUll terminate the string before returning it.
   s[index] = '\0';
   return s;
}

PS Don't ever use gets. See Why is the gets function so dangerous that it should not be used?. Use fgets if you need to read a line of text.

Upvotes: 2

P.P
P.P

Reputation: 121357

First of all, never use gets(). Use fgets() instead. gets() can't prevent if you overflow the buffer. It has been removed from the C standard C11.

Here,

 s = (char *)malloc(sizeof(char));

you are allocating memory for just a single char which is enough only for the null character to terminate the string. You need to allocate more space to read a line.

 s = malloc(256); //sizeof(char) is always 1. So you don't have to multiply it.
 if( fgets(s, 256, stdin) == NULL )  { /* handle failure */

fgets() also reads the newline if the buffer has sufficient space. So you may want to remove if it's not desired. You can remove it using strcspn():

s[strcspn(s,"\n")] = 0;

Upvotes: 2

Related Questions