Page 1 of 1

About EOF

Posted: Fri Apr 20, 2007 9:38 pm
by ranacse05
Hi
how can i take a string as input till EOF??

Posted: Fri Apr 20, 2007 10:01 pm
by jan_holmes

Code: Select all

string s;
while (cin >> s) {
	//statement
}
or

if you want to have a blank space(s), u can use :

Code: Select all

char s[255];
while (cin.getline(s,255)) {
        //statement
}
EDIT : oops... I didn't pay attention that both codes I wrote above are for C++ :oops:

Anyway u can use this for C :

Code: Select all

char s[255];
while (gets(s)) {
        //statement
}

Posted: Sat Jul 28, 2007 11:52 am
by KaDeG
Although as I know gets can be used to uva problems it is not recommended for programming. Just see this(from GCC):
/tmp/ccSVOabh.o: In function `main':
gets.c:(.text+0x1e): warning: the `gets' function is dangerous and should not be used.
so I would using something else. It's better using fgets like this:

Code: Select all

    char k[200];
        while(fgets(k, 200, stdin))     {
                printf("%s", k);
        }
Another way is:

Code: Select all

  char *string;, array[100];
        string=array;
        while(scanf("%s", string)!=EOF) {
                printf("%s\n", string);
        }
Hope helped

Posted: Sat Jul 28, 2007 11:59 am
by mf
KaDeG wrote:

Code: Select all

  char *string;, array[100];
        string=array;
        while(scanf("%s", string)!=EOF) {
                printf("%s\n", string);
        } 
This code is equally bad (dangerous, whatever) for exactly the same reason as gets(): you don't specify size of buffer to scanf, so a large enough input will cause buffer overflow.

(You can specify buffer size with something like scanf("%99s", ...), though)