About EOF

Write here if you have problems with your C source code

Moderator: Board moderators

Post Reply
ranacse05
New poster
Posts: 37
Joined: Wed Mar 28, 2007 5:08 pm
Location: Rajshahi
Contact:

About EOF

Post by ranacse05 » Fri Apr 20, 2007 9:38 pm

Hi
how can i take a string as input till EOF??
I like to solve problems.

jan_holmes
Experienced poster
Posts: 136
Joined: Fri Apr 15, 2005 3:47 pm
Location: Singapore
Contact:

Post by jan_holmes » Fri Apr 20, 2007 10:01 pm

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
}

User avatar
KaDeG
New poster
Posts: 13
Joined: Sun Mar 04, 2007 8:40 pm

Post by KaDeG » Sat Jul 28, 2007 11:52 am

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
/*No Comment*/

mf
Guru
Posts: 1244
Joined: Mon Feb 28, 2005 4:51 am
Location: Zürich, Switzerland
Contact:

Post by mf » Sat Jul 28, 2007 11:59 am

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)

Post Reply

Return to “C”