Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Infinite string (http://www.go4expert.com/forums/infinite-string-t21673/)

nk28 5Apr2010 20:56

Infinite string
 
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!!!

virxen 6Apr2010 00:06

Re: Infinite string
 
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.

xpi0t0s 6Apr2010 12:55

Re: Infinite string
 
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).

nk28 6Apr2010 21:30

Re: Infinite string
 
Thanxx.......
I'll try out the suggestions...................

niranjanvg 7Apr2010 19:29

Re: Infinite string
 
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;
}



All times are GMT +5.5. The time now is 15:47.