Page 1 of 1

data reading

Posted: Sun Jul 07, 2002 6:08 am
by htl
I've faced many data reading problems. The ways of giving data in almost every problem are different. Especially in multi input problems, they are nightmares to me. In 469, for example, you have to analyze if the input is data part or query part. And in 10324, you have to stop the program if you get '\n' or EOF. I'm troubled with these problems. I often gets RE instead of acceptd because of the data reading. Could someone share your experience and methods? And in what book I can find these information?

Posted: Sun Jul 07, 2002 6:41 am
by 10153EN
You can use gets.

If it's a blank line, the string get from gets is of strlen 0.
e.g. for a program runs until reading a blank line:
[c]char line[100000];
while(gets(line))
{
if(strlen(line) == 0) break;
......
}
[/c]

If it's the EOF, the gets returns NULL.
e.g. for a program runs until the EOF is read:
[c]char line[100000];
while(gets(line) != NULL)
{
......
}
[/c]

Hope can help~

Posted: Sun Jul 07, 2002 7:45 am
by htl
But gets() will crash if the buffer overflow. Maybe fgets is the better way of data reading?

Posted: Sun Jul 07, 2002 8:00 am
by 10153EN
Causing buffer overflow is the size of the string, but not choosing gets or fgets. Therefore to prevent buffer overflow, it's better to allocate an enough size of string size.

Re: data reading

Posted: Sat Mar 22, 2008 9:01 am
by zyxw
htl wrote:And in 10324, you have to stop the program if you get '\n' or EOF. I'm troubled with these problems.
The following snippet takes care of '\n' and EOF:

Code: Select all

 while(cin>>s)
 {
  // .....
 }