Infinite string

Discussion in 'C' started by nk28, Apr 5, 2010.

  1. nk28

    nk28 New Member

    Joined:
    Apr 5, 2010
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hello all;

    I want to take as an input a long string in C for my project.

    Could anyone suggest ways to go with it.Particularly if anyone can tell me whether taking the string using command line argument in main could help???????

    Thanxx!!!
     
  2. virxen

    virxen Active Member

    Joined:
    Nov 24, 2009
    Messages:
    387
    Likes Received:
    90
    Trophy Points:
    28
    give us an example of a long string ,in order to understand what you want to do

    generally you can use this
    Code:
    int buffer=2000;
    char mystring[buffer];
    fgets(mystring,buffer,stdin);
    
    entering a very big string from command line argument is not a good option.
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    If you don't need to store the entire string then you can just read it from input a character at a time. A lot of utilities are based around this kind of loop:
    Code:
    while ((c=getchar())!=EOF)
    {
      //...do something
    }
    
    which reads characters from stdin into c (defined as int) and terminates at the end of file, so pipe semantics can be used, and if your OS is Unix and you're entering data from the keyboard you can press Ctrl-D to stop (assuming of course Ctrl-D is setup to send EOF, which it normally is).
     
  4. nk28

    nk28 New Member

    Joined:
    Apr 5, 2010
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Thanxx.......
    I'll try out the suggestions...................
     
  5. niranjanvg

    niranjanvg New Member

    Joined:
    Apr 6, 2010
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Hi virxen,

    May be the following code will also help, but always make use that this structure is the last variable to be declared and the string is the last member of the structure, or else there is a danger of overwriting values of other memory locations

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    struct st {
    	int n;
    	char ar[];
    };
    int main() {
    	struct st *s;
    	s=(struct st*)malloc(sizeof(struct st));
    	printf("\n Enter the value");
    	scanf("%[^\n]s",s->ar);
    	printf("\n this is a demonstration of variable length array : %s",s->ar);
    	return 0;
    }
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice